Indicating multiple value in a Dict[] for type hints
Asked Answered
B

2

27

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

Barrio answered 2/1, 2018 at 1:5 Comment(1)
This is not support in [most] statically typed language either. Consider a Union (eg. "Record" or "Tuple") to decompose the types.Knitwear
B
43

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.

Borderer answered 2/1, 2018 at 1:10 Comment(1)
TypedDict was added in Python 3.8. The answer should be updated.Forswear
A
-1

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.

Actaeon answered 4/4 at 11:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.