从两个列表中创建字典时分配中的类型不兼容

问题描述

将两个列表加入字典时,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)

那是为什么?具体来说,第二个错误看起来令人困惑。

解决方法

尝试为dd = 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)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...