Skip to content

Instantly share code, notes, and snippets.

@victory-sokolov
Created January 15, 2024 13:59
Show Gist options
  • Save victory-sokolov/72c2b964e72231b5743c72d43159f32d to your computer and use it in GitHub Desktop.
Save victory-sokolov/72c2b964e72231b5743c72d43159f32d to your computer and use it in GitHub Desktop.
Python dictionary to TypedDict
from typing import TypedDict
# Define a regular dictionary
my_dict = {
"foo": 1,
"bar": "hello",
"baz": True,
}
# Create a TypedDict class by passing the dictionary keys and their corresponding types to the TypedDict constructor
MyTypedDict = TypedDict("MyTypedDict", {
"foo": int,
"bar": str,
"baz": bool,
})
# Create an instance of the TypedDict class by passing the regular dictionary to the constructor
my_typed_dict = MyTypedDict(my_dict)
# Access the dictionary values using the dot notation
print(my_typed_dict.foo) # Output: 1
print(my_typed_dict.bar) # Output: "hello"
print(my_typed_dict.baz) # Output: True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment