简体   繁体   English

python更新字典与循环中的字典

[英]python update dictionary with dictionary in loop

I am trying to update a dictionary with an other dictionary in a loop 我正在尝试与其他字典循环更新一个字典

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

Output: 输出:

>>> print mainDict
{'a': 1, 'b': 2}

What I am expecting is: 我期望的是:

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

Any suggestions please. 有任何建议请。 Thanks. 谢谢。

Dictionaries are key-value pairs. 字典是键值对。 In your expected output there is no dictionary. 在您的预期输出中没有字典。 Either you want a list , and in this case use: 您需要一个list ,在这种情况下,请使用:

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

or add keys in the loop: 或在循环中添加键:

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

As others commented in the comments section, python dictionaries keys must be unique. 正如其他人在评论部分中所述,python字典键必须唯一。 Quoting from python docs : 引用python docs

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) 最好将字典视为无序的:值对,并要求键是唯一的(在一个字典中)

Possible solution : Create a list instead of a dict to store the dictionaries. 可能的解决方案 :创建一个list而不是dict来存储字典。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM