gpt4 book ai didi

python - 根据条件对字典元素进行去重[Python]

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

我有一个字典如下:

dict = {
'key-1': [('blue', '-20'), ('red', '-67')],
'key-2': [('blue', '-77'), ('cyan', '-67'), ('white', '-57')],
'key-3': [('blue', '-39'), ('cyan , '-35'), ('purple', '-60')]
}

上面的字典包含带有元组(“颜色”,“权重”)的键。我想过滤列表,如果字典中有重复的颜色,则应保留权重最高的元组,并应从字典中弹出该颜色的所有其他事件。

在这种情况下,过滤后的字典应该如下所示:

filtered_dict = {
'key-1': [('blue', '-20'), ('red', '-67')],
'key-2': [('white', '-57')],
'key-3': [('purple', '-60'), ('cyan', '-35')]
}

字典是用颜色和权重动态生成的。我应该如何处理这个问题?

如有必要,可以更改字典的结构。

[编辑:权重为负数]

最佳答案

创建一个 max_dict 来保存所有颜色-最大键值对。然后遍历原始字典,将每个元组与 max_dict 进行比较。

key_dict = {
'key-1': [('blue', '20'), ('red', '67')],
'key-2': [('blue', '77'), ('cyan', '67'), ('white', '57')],
'key-3': [('blue', '39'), ('cyan' , '35'), ('purple', '60')]
}

# create a max_dict including all the key-value pairs of color-maximum value
max_dict = dict()

for color_list in key_dict.values():
for item in color_list:
if item[0] not in max_dict.keys():
max_dict.update({item[0]: int(item[1])})
else:
if int(item[1]) > max_dict[item[0]]:
max_dict.update({item[0]: int(item[1])})

# create a list to hold all the updated list of tuples from the original dictionary
list_of_values = []

# sort through the original dictionary, comparing each tuple to the max_dict key-value pairs
for color_list in key_dict.values():
list_of_tuples = []
for item in color_list:
if int(item[1]) == max_dict[item[0]]:
list_of_tuples.append(item)
list_of_values.append(list_of_tuples)

filtered_dict = dict(zip(key_dict.keys(), list_of_values))

输出:

>>> filtered_dict
{'key-1': [('red', '67')], 'key-2': [('blue', '77'), ('cyan', '67'), ('white', '57')], 'key-3': [('purple', '60')]}

关于python - 根据条件对字典元素进行去重[Python],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61264074/

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