簡體   English   中英

python更新字典與循環中的字典

[英]python update dictionary with dictionary in loop

我正在嘗試與其他字典循環更新一個字典

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

輸出:

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

我期望的是:

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

有任何建議請。 謝謝。

字典是鍵值對。 在您的預期輸出中沒有字典。 您需要一個list ,在這種情況下,請使用:

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

或在循環中添加鍵:

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

正如其他人在評論部分中所述,python字典鍵必須唯一。 引用python docs

最好將字典視為無序的:值對,並要求鍵是唯一的(在一個字典中)

可能的解決方案 :創建一個list而不是dict來存儲字典。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM