Note: typing.Dict has been deprecated as of Python 3.9, because the dict type itself can be used as a generic type directly (together with other standard containers). You can do the same in Python 3.7 or 3.8 if you use a from __future__ import annotations directive. My answer was originally written for much older Python 3 releases.


There is no real difference between using a plain typing.Dict and dict, no.

However, typing.Dict is a Generic type that lets you specify the type of the keys and values too, making it more flexible:

def change_bandwidths(new_bandwidths: typing.Dict[str, str],
                      user_id: int,
                      user_name: str) -> bool:

As such, it could well be that at some point in your project lifetime you want to define the dictionary argument a little more precisely, at which point expanding typing.Dict to typing.Dict[key_type, value_type] is a 'smaller' change than replacing dict.

You can make this even more generic by using Mapping or MutableMapping types here; since your function doesn't need to alter the mapping, I'd stick with Mapping. A dict is one mapping, but you could create other objects that also satisfy the mapping interface, and your function might well still work with those:

from collections.abc import Mapping

def change_bandwidths(new_bandwidths: Mapping[str, str],
                      user_id: int,
                      user_name: str) -> bool:

Now you are clearly telling other users of this function that your code won't actually alter the new_bandwidths mapping passed in.

Your actual implementation is merely expecting an object that is printable. That may be a test implementation, but as it stands your code would continue to work if you used new_bandwidths: object, because any object in Python is printable.

Answer from Martijn Pieters on Stack Overflow
🌐
Python documentation
docs.python.org › 3 › library › typing.html
typing — Support for type hints
1 week ago - Changed in version 3.8: The _field_types and __annotations__ attributes are now regular dictionaries instead of instances of OrderedDict.
Top answer
1 of 5
387

Note: typing.Dict has been deprecated as of Python 3.9, because the dict type itself can be used as a generic type directly (together with other standard containers). You can do the same in Python 3.7 or 3.8 if you use a from __future__ import annotations directive. My answer was originally written for much older Python 3 releases.


There is no real difference between using a plain typing.Dict and dict, no.

However, typing.Dict is a Generic type that lets you specify the type of the keys and values too, making it more flexible:

def change_bandwidths(new_bandwidths: typing.Dict[str, str],
                      user_id: int,
                      user_name: str) -> bool:

As such, it could well be that at some point in your project lifetime you want to define the dictionary argument a little more precisely, at which point expanding typing.Dict to typing.Dict[key_type, value_type] is a 'smaller' change than replacing dict.

You can make this even more generic by using Mapping or MutableMapping types here; since your function doesn't need to alter the mapping, I'd stick with Mapping. A dict is one mapping, but you could create other objects that also satisfy the mapping interface, and your function might well still work with those:

from collections.abc import Mapping

def change_bandwidths(new_bandwidths: Mapping[str, str],
                      user_id: int,
                      user_name: str) -> bool:

Now you are clearly telling other users of this function that your code won't actually alter the new_bandwidths mapping passed in.

Your actual implementation is merely expecting an object that is printable. That may be a test implementation, but as it stands your code would continue to work if you used new_bandwidths: object, because any object in Python is printable.

2 of 5
43

typing.Dict is a generic version of dict:

class typing.Dict(dict, MutableMapping[KT, VT])

A generic version of dict. The usage of this type is as follows:

def get_position_in_index(word_list: Dict[str, int], word: str) -> int:
     return word_list[word]

Here you can specify the type of key and values in the dict: Dict[str, int]

Discussions

How to type hint dictionaries without using Any?
When data structures are difficult to type hint, it is often an indication that the data structure could be refactored to a better structure. More on reddit.com
🌐 r/learnpython
16
4
February 28, 2024
How to set the python type hinting for a dictionary variable? - Stack Overflow
Dict and List are ugly and remind me of Java. 2021-10-02T20:35:31.593Z+00:00 ... @BurgerBurglar I WISH more of python reminded me of Java... :D Changing the case of a reference class to lower case because it is prettier rather than referencing the class that defines the type you wish to type hint ... More on stackoverflow.com
🌐 stackoverflow.com
Untyped dict & walrus type hints - Ideas - Discussions on Python.org
Hello, using Python 3.10.12, I have a couple of ideas about type hints for you to ponder. Adding type hints to key/value iteration over items of a dictionary whose type is unknown: for key:'str', value:'int' in unty… More on discuss.python.org
🌐 discuss.python.org
0
October 1, 2023
How to Set Type Hinting for a Dictionary in Python - TestMu AI Community
How do I set Python type hinting for a dictionary variable? Let’s say I have a dictionary like this: from typing import Dict v = { 'height': 5, 'width': 14, 'depth': 3 } result = do_something(v) def do_something(value: Dict[???]): # do stuff How do I declare the dictionary type in do_something ... More on community.testmuai.com
🌐 community.testmuai.com
0
January 16, 2025
🌐
Mypy
mypy.readthedocs.io › en › stable › cheat_sheet_py3.html
Type hints cheat sheet - mypy 1.19.1 documentation
# For most types, just use the name of the type in the annotation # Note that mypy can usually infer the type of a variable from its value, # so technically these annotations are redundant x: int = 1 x: float = 1.0 x: bool = True x: str = "test" x: bytes = b"test" # For collections on Python 3.9+, the type of the collection item is in brackets x: list[int] = [1] x: set[int] = {6, 7} # For mappings, we need the types of both keys and values x: dict[str, float] = {"field": 2.0} # Python 3.9+ # For tuples of fixed size, we specify the types of all the elements x: tuple[int, str, float] = (3, "yes
🌐
Python
peps.python.org › pep-0589
PEP 589 – TypedDict: Type Hints for Dictionaries with a Fixed Set of Keys | peps.python.org
PEP 484 defines the type Dict[K, V] for uniform dictionaries, where each value has the same type, and arbitrary key values are supported. It doesn’t properly support the common pattern where the type of a dictionary value depends on the string value of the key.
🌐
Python documentation
docs.python.org › 3 › library › stdtypes.html
Built-in Types — Python 3.14.3 documentation
6 days ago - The only operation that immutable sequence types generally implement that is not also implemented by mutable sequence types is support for the hash() built-in. This support allows immutable sequences, such as tuple instances, to be used as dict keys and stored in set and frozenset instances.
🌐
Medium
pavolkutaj.medium.com › explaining-type-hints-for-dictionaries-in-python-187d712df631
Explaining Type Hints for Dictionaries in Python | by Pavol Z. Kutaj | Medium
June 8, 2023 - Dict[str, str] is a type hint in Python that indicates a dictionary where the keys and values are both of type str.
Find elsewhere
🌐
FastAPI
fastapi.tiangolo.com › python-types
Python Types Intro - FastAPI
These "type hints" or annotations are a special syntax that allow declaring the type of a variable. By declaring types for your variables, editors and tools can give you better support.
🌐
Adam Johnson
adamj.eu › tech › 2021 › 05 › 10 › python-type-hints-how-to-use-typeddict
Python type hints: How to Use TypedDict - Adam Johnson
May 10, 2021 - We can use the typing union operator, |, to declare the possible types of values: from __future__ import annotations def get_sales_summary() -> dict[str, int | str | list[str]]: ...
🌐
Dagster
dagster.io › blog › python-type-hinting
Using Type Hinting in Python Projects
August 11, 2023 - from typing import Optional def find_student(student_id: int) -> Optional[dict[str, str]]: # If the student is found, return a dictionary containing their data # If the student is not found, return None · The Union type hint is used to indicate that a variable can be one of several types. For example, if a variable can be either a str or an int, you can provide a type hint like this: from typing import Union def process(data: Union[str, int]) -> None: # This function can handle either a string or an integer · In newer versions of Python, you can use the pipe (|) operator to indicate a type that can be one of several options, replacing the need for Union:
🌐
Python
peps.python.org › pep-0484
PEP 484 – Type Hints | peps.python.org
get_type_hints(), a utility function to retrieve the type hints from a function or method. Given a function or method object, it returns a dict with the same format as __annotations__, but evaluating forward references (which are given as string ...
🌐
Reddit
reddit.com › r/learnpython › how to type hint dictionaries without using any?
r/learnpython on Reddit: How to type hint dictionaries without using Any?
February 28, 2024 -

Hi folks I tried to keep the title as short and concise as possible, I often find myself struggling for hours in order to properly type annotate nested dictionaries in my code.

If the dict only has 1 level, it works well but with a tiny more complex ones like the following, I have a lot of trouble:

{"@context": "http://schema.org",
 "@type": "VideoObject",
 "url": "https://www.example.com/0000/adventures-music-videos.html",
 "name": "sample movie",
 "description": "example",
 "thumbnailUrl": "thumbnail.com/1.jpg",
 "uploadDate": "2023-11-29",
 "duration": "PT2H20M20S",
 "contentUrl": "sample_link",
 "isAccessibleForFree": false,
 "productionCompany": {"@type": "Organization",
  "name": "Example",
  "@id": "https://www.example.com/0000/studio/music-movies.html"},
 "hasPart": [{"@type": "Clip",
   "name": "scene 1",
   "startOffset": 15,
   "endOffset": 2126,
   "url": "https://www.example.com/0000/adventures-music-videos.html#scene_0000",
   "isAccessibleForFree": false},
  {"@type": "Clip",
   "name": "scene 2",
   "startOffset": 2128,
   "endOffset": 4114,
   "url": "https://www.example.com/0000/adventures-music-videos.html#scene_0000",
   "isAccessibleForFree": false},
  {"@type": "Clip",
   "name": "scene 3",
   "startOffset": 4117,
   "endOffset": 6055,
   "url": "https://www.example.com/0000/adventures-music-videos.html#scene_0000",
   "isAccessibleForFree": false},
  {"@type": "Clip",
   "name": "scene 4",
   "startOffset": 6057,
   "endOffset": 8414,
   "url": "https://www.example.com/0000/adventures-music-videos.html#scene_0000",
   "isAccessibleForFree": false}]}

I tried dict[str, object] and I also tried a looong annotation with all the possible types separated by a pipe, but for now the only one that does not trigger mypy in strict mode is dict[str, Any].

Any clues as to what I might be doing wrong?

🌐
Python.org
discuss.python.org › ideas
Untyped dict & walrus type hints - Ideas - Discussions on Python.org
October 1, 2023 - Hello, using Python 3.10.12, I have a couple of ideas about type hints for you to ponder. Adding type hints to key/value iteration over items of a dictionary whose type is unknown: for key:'str', value:'int' in untyped_dict.items(): ... Adding type hints to the walrus operator would also come in handy with untyped dicts: if status_code:'str' := untyped_dict.get('status_code', ''): ... Please note that this is not a request to find a workaround for the lack of these features.
🌐
TestMu AI Community
community.testmuai.com › ask a question
How to Set Type Hinting for a Dictionary in Python - TestMu AI Community
January 16, 2025 - How do I set Python type hinting for a dictionary variable? Let’s say I have a dictionary like this: from typing import Dict v = { 'height': 5, 'width': 14, 'depth': 3 } result = do_something(v) def do_something(value: Dict[???]): # do stuff How do I declare the dictionary type in do_something ...
🌐
InfoWorld
infoworld.com › home › software development › programming languages › python
Get started with Python type hints | InfoWorld
June 18, 2025 - In this case, we have a dictionary that takes ints as keys, but either ints or strs as values. The user_id variable (which we could use to compare against the dictionary’s keys) can be an int or None (“no valid user”), but not a str. In Python 3.10 and higher, Union types can be hinted using the pipe character as follows, with no imports needed:
🌐
Rittman Mead
rittmanmead.com › blog › 2024 › 03 › tip-tuesday-python-data-type-hints
Tip Tuesday | Python Data Type Hints
March 26, 2024 - Type hints can also specify composite types like lists, tuples, dictionaries, and sets.
🌐
FastAPI Tutorial
fastapitutorial.com › blog › advanced-type-hints
2. Advanced Type Hints
new_price: list[int] = [14,902,898] new_immutable_price: tuple[int,int,int] = (388,392,299) new_price_dict: dict[str,int] = { "item_1":240, "item_2":490, } 2. Annotating with complex data structures ⚠️ For now, I am proceeding with the older and established syntax for type annotations. Python does support a newer way to write type hints but there are some issues with it.
🌐
Python Forum
python-forum.io › thread-16557.html
What is the correct type hint when you want to accept Iterable but not Dictionary
How would I indicate, using a type hint, that the function only works with a List type data structure containing only int? I researched a little deeper and from the documentation, I found: Quote:An object capable of returning its members one at a...
🌐
Like Geeks
likegeeks.com › home › python › python dictionary type hinting: from dict to typeddict
Python Dictionary Type Hinting: From Dict to TypedDict
November 18, 2024 - To hint at a simple dictionary, use the dict keyword along with types for keys and values.