我有一本字典,内容如下:
dict = {
'key-1': [('blue', '-20'), ('red', '-67')],
'key-2': [('blue', '-77'), ('cyan', '-67'), ('white', '-57')],
'key-3': [('blue', '-39'), ('cyan , '-35'), ('purple', '-60')]
}上面的字典包含带有元组(“color”,“weight”)的键。我想过滤列表,这样如果一个颜色在字典中重复,那么具有最高权重的元组应该被保留,并且应该从字典中弹出该颜色的所有其他出现。
在这种情况下,过滤后的字典应该如下所示:
filtered_dict = {
'key-1': [('blue', '-20'), ('red', '-67')],
'key-2': [('white', '-57')],
'key-3': [('purple', '-60'), ('cyan', '-35')]
}字典是用颜色和权重动态生成的。我应该如何处理这个问题?
如有必要,可以改变形成字典的结构。
编辑:权重为负数
发布于 2020-04-17 12:27:26
您可以使用collections.defaultdict构建一个包含每种颜色的所有最大权重的字典
from collections import defaultdict
dic = {
'key-1': [('blue', '-20'), ('red', '-67')],
'key-2': [('blue', '-77'), ('cyan', '-67'), ('white', '-57')],
'key-3': [('blue', '-39'), ('cyan' , '-35'), ('purple', '-60')]
}
color_weight_groups = defaultdict(list)
for lst in dic.values():
for color, weight in lst:
color_weight_groups[color].append(weight)
max_weights = {k: max(map(int, v)) for k, v in color_weight_groups.items()}
print(max_weights)它将看起来像这样:
{'blue': -20, 'red': -67, 'cyan': -35, 'white': -57, 'purple': -60}然后创建一个新的字典,将每个权重与最大权重进行比较:
result = {
k: [(color, weight) for color, weight in v if int(weight) == max_weights[color]]
for k, v in dic.items()
}
print(result)这给出了过滤后的结果:
{'key-1': [('blue', '-20'), ('red', '-67')], 'key-2': [('white', '-57')], 'key-3': [('cyan', '-35'), ('purple', '-60')]}发布于 2020-04-17 12:36:20
创建一个包含所有颜色最大键值对的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')]}https://stackoverflow.com/questions/61264074
复制相似问题