23

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)]

Mamun
  • 66,969
  • 9
  • 47
  • 59
Nijan
  • 568
  • 1
  • 5
  • 14
  • This is not support in [most] statically typed language either. Consider a Union (eg. "Record" or "Tuple") to decompose the types. – user2864740 Jan 02 '18 at 02:08

1 Answers1

39

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.

Siete
  • 328
  • 3
  • 14
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • 13
    [`TypedDict`](https://docs.python.org/3/library/typing.html#typing.TypedDict) was added in Python 3.8. The answer should be updated. – Georgy Jul 12 '20 at 14:10