Skip to content

semav-techdev/Python-TypedDict

Repository files navigation

TypedDict in Python (Check typing) 🐍

If you see typedDict in somewhere or try to use it , you will first see it's look like a regular dictionary, so you might wonder , what's the difference 🤔?

So let's the first thing be clarify this wondering , because if you understand the different between them it's will be easy to you to use it.

In Python, both Dictionary and TypedDict store key–value pairs — but they serve very different purposes.

🔑 Dictionary (dict) :

  • Completely flexible
  • Keys and values can be of any type
  • Great for quick data storage
  • ❌ No type checking → mistakes are caught only at runtime

🔑 TypedDict

  • Introduced for type safety

  • Allows you to define expected keys and their types

  • Helps catch bugs before running the code(via type checkers like mypy)

  • Perfect for large projects and API data structures Example:

    from typing import TypedDict
    class User(TypedDict):
        name: str
        age: int
    

    You see that the dictionary no type checking .

🚀why use TypedDict?

Python is a dynamic language ,so we don't have to specify types.

However type hint are useful because they:

  • Don’t slow down your code.
  • Don’t change your code’s behavior.
  • Make bugs easier to find before you even run the program.
  • Improve readability and collaboration

TypedDict is a type recognized by Python type checker such as mypy. It describes a structured dictionary/map with an expected set of named string keys mapped to values of particular expected types.

🌐 Real-world Example (API Response)

Such structures are ubiquitous when exchanging JSON data, which is common for Python web applications to do.

For example, a web API for fetching TV show ratings may return a JSON response that looks like:

{
    "title": "Queen's Gambit",
    "stars": 5
}

That API probably always returns responses in a particular generic shape:

{
    "title": <some str>,
    "stars": <some int>
}

and that shape can be described by a TypedDict definition:

from typing import TypedDict

class MediaRating(TypedDict):
    title: str
    stars: int

With that TypedDict definition in place, you can take any JSON value received from that API and use it directly in Python, without any additional conversions or additional parsing. More Details

🚀 TypedDict types:

There are two syntaxes: class-based and function-based syntax.

By default, all keys are required.

so sometimes we will have a Problem Missing Key in TypedDict like :

from typing import TypedDict
A = TypedDict('A', {'x': int, 'y': str})
a: A = {'x': 1}# Error

So here A expect x and y and we just give it x and y is missing key.

To make keys optional we use:

total : a boolean literal (True or False) indicating whether all items are required or not required. total=True → required (the default)

total=False → not required

Use total=False to make keys optional

closed: a boolean literal (True or False) indicating whether the TypedDict is closed (True) or open (False).

closed=True → only the defined keys are allowed

closed=False → extra keys are allowed (default behavior)

extra_items: indicates that the TypedDict has extra items. The argument must be a annotation expression specifying the type of the extra items.if closed=False what type of it

class User(TypedDict, closed=False, extra_items=str):
      name: str

see here for more details

🚀Structural compatibility

Mypy uses structural compatibility with TypedDicts. A TypedDict with extra items is compatible with a narrower TypedDict so :

  • More keys → used as fewer keys.
  • Fewer keys → used as more keys. see example

🚀Unions of TypedDicts

label or tag your TypedDicts with a distinct Literal type. Then, you can discriminate between each kind of TypedDict by checking the label. see here

TypedDict with Generic see

📚 Resources

Official (dict)

Official (typeddict)

David Foster who create (typedDict)

TypedDict vs Dictionary

Keyword argument for typedDict

TypedDict and Generic

About

Python programs often use dictionaries with string keys to represent objects. TypedDict lets you give precise types for dictionaries with a fixed schema

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages