Sti*_*ack 3 python dictionary strong-typing
这里已经有一个很棒的问答,用于在 python 中创建非类型化字典。我正在努力弄清楚如何创建类型字典然后向其中添加内容。
我想做的一个例子是......
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
Run Code Online (Sandbox Code Playgroud)
...但这让我犯了一个错误descriptor 'update' requires a 'dict' object but received a 'str'
我尝试了上述声明的一些其他排列
return_value:Dict[str,str] = None
Run Code Online (Sandbox Code Playgroud)
错误与'NoneType' object has no attribute 'update'. 并尝试
return_value:Dict[str,str] = dict()
Run Code Online (Sandbox Code Playgroud)
或者
return_value:Dict[str,str] = {}
Run Code Online (Sandbox Code Playgroud)
两个错误都与update expected at most 1 arguments, got 2. 我不知道这里需要什么来创建一个空的类型字典,就像在 c# ( var d = new Dictionary<string, string>();) 中一样。如果可能的话,我宁愿不回避类型安全。有人可以指出我遗漏了什么或做错了什么吗?
最后两个是 的正确用法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
Run Code Online (Sandbox Code Playgroud)