Search code examples
pythonpython-typingmypy

Incompatible types in assignment when creating a dict out of two lists


When joining two lists into a dict, mypy complains about incompatible types in the assignment. Like this:

from typing import Dict
d = Dict[str, int]

ln = ['a', 'b', 'c']
lc = [3, 5, 7]
d = dict(zip(ln, lc))
print(ln)
print(lc)
print(d)

The output shows that it's working alright:

% python3 blurb.py
['a', 'b', 'c']
[3, 5, 7]
{'a': 3, 'b': 5, 'c': 7}

But mypy shows:

% mypy blurb.py
blurb.py:6: error: Cannot assign multiple types to name "d" without an explicit "Type[...]" annotation
blurb.py:6: error: Incompatible types in assignment (expression has type "Dict[str, int]", variable has type "Type[Dict[Any, Any]]")
Found 2 errors in 1 file (checked 1 source file)

Why is that? Specificylly the second error looks confusing.


Solution

  • Try using different variable name instead of d for d = dict(zip(ln, lc)) or d = Dict[str, int].

    E.g.

    from typing import Dict
    d = Dict[str, int]
    
    ln = ['a', 'b', 'c']
    lc = [3, 5, 7]
    x: d = dict(zip(ln, lc))
    print(ln)
    print(lc)
    print(x)