在循环中使用字典更新字典

2024-03-28 22:36:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在循环中用另一个词典更新一个词典

    mainDict = {}
    for index in range(3):
        tempDict = {}
        tempDict['a'] = 1
        tempDict['b'] = 2
        mainDict.update(tempDict)

输出:

^{pr2}$

我期待的是:

{{'a': 1, 'b': 2},{'a': 1, 'b': 2},{'a': 1, 'b': 2}}    

有什么建议吗。谢谢。在


Tags: inforindexupdaterange建议词典pr2
2条回答

字典是键值对。在您的预期输出中没有字典。您需要一个list,在本例中使用:

main_list = []
for (...)
    main_list.append(temp_dict)

或在循环中添加关键点:

^{pr2}$

正如其他人在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来存储字典。在

相关问题 更多 >