2024-03-28 22:36:30 发布
网友
我正在循环中用另一个词典更新一个词典
mainDict = {} for index in range(3): tempDict = {} tempDict['a'] = 1 tempDict['b'] = 2 mainDict.update(tempDict)
输出:
我期待的是:
{{'a': 1, 'b': 2},{'a': 1, 'b': 2},{'a': 1, 'b': 2}}
有什么建议吗。谢谢。在
字典是键值对。在您的预期输出中没有字典。您需要一个list,在本例中使用:
list
main_list = [] for (...) main_list.append(temp_dict)
或在循环中添加关键点:
正如其他人在comments部分中评论的那样,python字典的键必须是唯一的。引自pythondocs:
It is best to think of a dictionary as an unordered set of key: value pairs, with the requirement that the keys are unique (within one dictionary)
可能的解决方案:创建list而不是dict来存储字典。在
dict
字典是键值对。在您的预期输出中没有字典。您需要一个
list
,在本例中使用:或在循环中添加关键点:
^{pr2}$正如其他人在comments部分中评论的那样,python字典的键必须是唯一的。引自pythondocs:
可能的解决方案:创建
list
而不是dict
来存储字典。在相关问题 更多 >
编程相关推荐