How do I express the type of a Dict
which has two keys that take two different types of values? For example:
a = {'1': [], '2': {})
The following is just to give you an idea of what I am looking for.
Dict[(str, List), (str, Set)]
How do I express the type of a Dict
which has two keys that take two different types of values? For example:
a = {'1': [], '2': {})
The following is just to give you an idea of what I am looking for.
Dict[(str, List), (str, Set)]
The feature you are asking about is called "Heterogeneous dictionaries" where you need to define specific types of values for the specific keys. The issue was being discussed at Type for heterogeneous dictionaries with string keys and is now made available in Python 3.8. You can now use the TypedDict
which will allow a syntax like:
class HeterogeneousDictionary(TypedDict):
x: List
y: Set
For older Python versions, at the very least, we can ask for values to be either List
or Set
using Union
:
from typing import Dict, List, Set, Union
def f(a: Dict[str, Union[List, Set]]):
pass
This is, of course, not ideal as we lose a lot of information about what keys need to have values of which types.
TypedDict
was added in Python 3.8. The answer should be updated. –
Forswear The Dict type still exists, but is a depricated alias to dict. Since Python 3.9, dictionaries can be type hinted with x: dict[str, str]
.
To signal that a variable can contain multiple types, you can use the Union type from the typing standard library. However, since Python 3.10, the | operator can be used on type objects to annotate that a variable can contain multiple types.
To answer your question, a: dict[str, list[str] | set[str]]
Note that this can be used for return values, but Mapping and MutableMapping are preferred for arguments. Besides, a list and set can also share a type depending on the operations. For this, Sequence or Iterable is preferred.
A great article covering the basics of type annotating list and dictionaries can be found here.
© 2022 - 2024 — McMap. All rights reserved.