Mypy Invalid index type "str" for "Union[str, Dict[str, str]]"; expected type "Union[int, slice]"

Viewed 2432

Why am I getting the error? I have added the type properly, right?

Invalid index type "str" for "Union[str, Dict[str, str]]"; expected type "Union[int, slice]"

Code

from typing import List, Dict, Union

d = {"1": 1, "2": 2}

listsOfDicts: List[Dict[str, Union[str, Dict[str, str]]]] = [
    {"a": "1", "b": {"c": "1"}},
    {"a": "2", "b": {"c": "2"}},
]

[d[i["b"]["c"]] for i in listsOfDicts]
1 Answers

Mypy expects dictionaries to have the same type. Using Union models a subtype relation, but since Dict type is invariant, the key-value pair must match exactly as defined in the type annotation—which is the type Union[str, Dict[str, str]], so the subtypes in the Union wouldn't get matched (neither str, Dict[str, str] are valid types).

To define multiple types for different keys, you should use TypedDict.

Usage as seen here: https://mypy.readthedocs.io/en/latest/more_types.html#typeddict.

from typing import List, Dict, Union, TypedDict

d = {"1": 1, "2": 2}

dictType = TypedDict('dictType', {'a': str, 'b': Dict[str, str]})

listsOfDicts: List[dictType] = [
    {"a": "1", "b": {"c": "1"}},
    {"a": "2", "b": {"c": "2"}},
]

[d[i["b"]["c"]] for i in listsOfDicts]
Related