在python中,我正在尋找一種方法來從包含重複鍵的文件中加載靜態聲明的字典時收到警告或錯誤,對於我的用例,該文件來自用戶輸入,所以我想確保我收到的字典沒有重複的密鑰。在load dictionary1與dictionary 2相同並且python字典保留最右邊的鍵/值對之後,我得到了這個結果。我正在尋找的是一種在加載之前或加載過程中發出警告或錯誤的方式,表示dictionary1有多個重複的「a」鍵。Python識別重複的字典鍵
dictionary1 = {"a":1, "a":2, "a":3}
dictionary2 = {"a":3}
,我能想到的是使用字典的列表,然後將每個字典最終字典,如下面的例子中的最好的辦法。這可行,但字典列表不像標準字典那樣用戶友好。
listofDicts = [{"a":1},{"a":2},{"a":3}]
masterDict = {}
for entry in listofDict:
for subDict in entry:
if subDict in masterDict.keys():
print ("ERROR key \"%s\" already exists with value %d" % (subDict, masterDict[subDict]))
else:
masterDict.update({subDict:entry[subDict]})
什麼是你的文件的格式?作爲旁邊的 –
,'如果masterDict.keys()中的子字典:'是反模式。你正在爲'masterDict'中的所有鍵創建一個'list',然後在該列表上做一個O(N)操作的成員測試,但是如果你剛剛完成了'if subDict in masterDict',有O(1)字典密鑰成員資格測試。 –
使用'json.loads'解析你的文件,然後參考這裏發佈的答案: http://stackoverflow.com/questions/14902299/json-loads-allows-duplicate-keys-in-a-dictionary-overwriting -the-first-value –