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 feature you are asking about is called "Heterogeneous dictionaries" where you need to define specific types of values for the specific keys. The issue is being discussed at Type for heterogeneous dictionaries with string keys and is not yet implemented and is still open. The current idea is to use so-called TypedDict
which would allow a syntax like:
class HeterogeneousDictionary(TypedDict):
x: List
y: Set
Note that mypy project has this type already available through the "mypy extensions" (marked as experimental) - TypedDict:
from mypy_extensions import TypedDict
HeterogeneousDictionary = TypedDict('HeterogeneousDictionary', {'1': List, '2': Set})
At the very least though, 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.