问题描述
将两个列表加入字典时,mypy
抱怨分配中的类型不兼容。像这样:
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)
输出表明它可以正常工作:
% python3 blurb.py
['a','c']
[3,7]
{'a': 3,'b': 5,'c': 7}
但是mypy
显示:
% 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)
那是为什么?具体来说,第二个错误看起来令人困惑。
解决方法
尝试为d
或d = dict(zip(ln,lc))
使用不同的变量名代替d = Dict[str,int]
。
例如
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)