Created
January 15, 2024 13:59
-
-
Save victory-sokolov/72c2b964e72231b5743c72d43159f32d to your computer and use it in GitHub Desktop.
Python dictionary to TypedDict
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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