有一个很棒的Q/A here already用于在 python 中创建 untyped 字典。我正在努力弄清楚如何创建一个 typed 字典,然后向其中添加内容。
我正在尝试做的一个例子是......
return_value = Dict[str,str]
for item in some_other_list:
if item.property1 > 9:
return_value.update(item.name, "d'oh")
return return_value
... 但这给我一个错误 descriptor 'update' requires a 'dict' object but received a 'str'
我已经尝试了上述声明的其他几种排列方式
return_value:Dict[str,str] = None
'NoneType' object has no attribute 'update'
的错误.并尝试
return_value:Dict[str,str] = dict()
或
return_value:Dict[str,str] = {}
两个错误与 update expected at most 1 arguments, got 2
.我不知道这里需要什么来创建一个空类型的字典,就像我在 c# ( var d = new Dictionary<string, string>();
) 中那样。如果可能的话,我宁愿不回避类型安全。有人可以指出我遗漏了什么或做错了什么吗?
最佳答案
最后 2 个是 Dict
的正确用法,但是您在 for 循环中使用不正确的语法更新了字典。
return_value: Dict[str, str] = dict()
for item in some_other_list:
if item.property1 > 9:
return_value[item.name] = "d'oh"
return return_value
关于python - 如何创建一个新的 typing.Dict[str,str] 并向其中添加项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55755398/