python - 如何创建一个新的 typing.Dict[str,str] 并向其中添加项目

标签 python dictionary strong-typing

有一个很棒的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/

相关文章:

python - 在 Python 中组合两个排序列表

python - 确定 python struct/pack fmt 字符串中的元素数量?

python - 字典的三元运算

multithreading - 如何安全地将新的键值对添加到原生 map 中

c# - 如何在 C# WinForms 中强类型数据绑定(bind)?

.net - ListBox.DisplayMember = [String] 我可以以某种方式解决它而不是 .NET 中的字符串吗?

java - Apache Spark : Pre requisite questions

python - 从字典列表中提取所有键

python - 将多个字典元素追加到列表中

c# - 将对象格式化为主题和正文的通用方法?