字典包含重复键,需自动修复帮助

0 投票
4 回答
80 浏览
提问于 2025-04-12 01:47

我为我正在制作的程序创建了一个包含1万行的字典,其中一些条目有重复的键,因为数据需要以特定的方式呈现。
解决这个问题的方法是把“值”变成一个列表,这样就可以去掉重复的键。
我在想有没有什么自动化的方法可以做到这一点?(在PyCharm中)

举个例子:

dict = {
"A": "Red",
"A": "Blue",
"A": "Green",
"B": "Yellow",
"C": "Black"
}

想要的输出:

dict = {
"A": ["Red","Blue","Green"],
"B": "Yellow",
"C": "Black"
}

我试过使用ChatGPT和手动处理 :D
我在寻找更聪明的方法来做到这一点,并学习新的方法。

4 个回答

0

我觉得字典(dict)这个数据类型不太适合你。我建议你使用一个元组的列表。

list_of_tuples = [("A", "Red"), ("A", "Blue"), ("A", "Green"), ("B", "Yellow"), ..]

如果你有重复的键,后面的键会覆盖前面的键。

我假设你把数据存储在一个txt文件里,这里有个建议:

要把你的“字典”转换成 list_of_tuples,你可以先把它转换成一个列表。

sample_list = ["A", "Red", "A", "Blue", "A", "Green", "B", "Yellow", ..]

这样做会更简单,你可以在存储你那1万行“字典”的文件里,把 : 符号替换成 , 符号,并把结尾的花括号({})替换成方括号([])。

然后你就可以把它转换成元组的列表了。

a = iter(sample_list)
list_of_tuples = list(zip(a, a))
# Output will be: list_of_tuples = [("A", "Red"), (A", "Blue"), ("A", "Green"), 
0

Python中的字典不允许有重复的键,比如下面这行代码会被这样处理

>>> d = {"a": 2, "a": 3, "b": 4}
>>> print(d)
{'a': 3, 'b': 4}

我不知道你是怎么在Python中生成这样的字典的,也许如果你提供一下你的原始数据格式,我们可以想出一个解决办法。

假设你有一个字符串,你可以这样做

j = '{"A": "Red", "A": "Blue", "A": "Green", "B": "Yellow", "C": "Black"}'

# Remove the surrounding curly braces from the string
j = j[1:-1]

# Split the string into key-value pairs
pairs = [pair.strip().replace('"', '') for pair in j.split(',')]

new_dict = {}

# Loop through the extracted key-value pairs
for pair in pairs:
    key, value = pair.split(':')
    key = key.strip()
    value = value.strip().strip('"')

    if key not in new_dict:
        new_dict[key] = value  # If key is not already in new_dict, create a list with the value
    else:
        if type(new_dict[key]) != list:
            new_dict[key] = [new_dict[key]]
        new_dict[key].append(value)  # If key already exists, append the value to the list

# Print the transformed dictionary
print(new_dict)
3

在Python的字典里,如果你有多个相同的键,后面的项会覆盖前面的项,所以最后你的字典里只会有一个键为"A"的项。

我建议你试着把这些内容放在一个表达式里,然后简单地解析一下,这样一个项是键,接下来是数据,再接下来又是键,依此类推。

你可以通过把":"替换成","来简单实现这一点,就像我在下面的代码中做的那样。

array = ("A", "Red", "A", "Blue", "A", "Green", "B", "Yellow", "C", "Black", "B", "smth")


def parse_dictionary(array):
    dictionary = {}
    for item_key, item in zip(array[::2], array[1::2]):
        if item_key in dictionary:
            if type(dictionary[item_key]) == list:
                dictionary[item_key].append(item)
            else:
                a = dictionary[item_key]
                dictionary[item_key] = [a, item]
        else:
            dictionary[item_key] = item
    return dictionary

撰写回答