gpt4 book ai didi

Python 识别重复的字典键

转载 作者:行者123 更新时间:2023-12-01 03:00:22 25 4
gpt4 key购买 nike

在Python中,我正在寻找一种在从包含重复键的文件加载静态声明的字典时接收警告或错误的方法,对于我的用例,该文件来自用户输入,所以我想确保字典我接收没有重复的 key 。我发现加载字典 1 后与字典 2 相同,并且 python 字典保留最右边的键/值对。我正在寻找一种在加载之前或加载期间收到警告或错误的方法,这表明dictionary1有多个重复的“a”键。

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]})

最佳答案

您可以使用 ast 模块解析包含字典的文件中的 Python 源代码,并查找具有重复键的字典文字:

import ast
import logging

class DuplicateKeyVisitor(ast.NodeVisitor):
def visit_Dict(self, node):
seen_keys = set()

for key_node in node.keys:
try:
key = ast.literal_eval(key_node)
except ValueError:
continue

if key in seen_keys:
logging.warning('Dictionary literal at (%d, %d) has duplicate keys', node.lineno, node.col_offset)

seen_keys.add(key)

DuplicateKeyVisitor().visit(ast.parse('''
foo = {'a': 1, 'a': 2}
bar = {'a': 1, 'b': 2}
bar = {'a': 1, 'b': 2, 'a': 3}
'''))

关于Python 识别重复的字典键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43906396/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com