在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 –