我有一个这样的字典列表:
[{'ID': 'a', 'Number': 2}, {'ID': 'b', 'Number': 5} , {'ID': 'a', 'Number': 6}, {'ID': 'a', 'Number': 8}, {'ID': 'c', 'Number': 3}]
我想删除具有相同键的字典,只保留最小的那个。预期结果应为:
[{'ID': 'a', 'Number': 2}, {'Id': 'b', 'Number': 5}, {'ID': 'c', 'Number': 3}]
答案 0 :(得分:1)
最有效的解决方案是使用临时查找字典,其关键字为ID
,值作为当前字典,其最低Number
对应于ID
。
l = [{'ID': 'a', 'Number': 2},
{'ID': 'b', 'Number': 5}, # note that I corrected a typo Id --> ID
{'ID': 'a', 'Number': 6},
{'ID': 'a', 'Number': 8},
{'ID': 'c', 'Number': 3}]
lookup_dict = {}
for d in l:
if d['ID'] not in lookup_dict or d['Number'] < lookup_dict[d['ID']]['Number']:
lookup_dict[d['ID']] = d
output = list(lookup_dict.values())
将output
设为:
[{'ID': 'a', 'Number': 2}, {'ID': 'b', 'Number': 5}, {'ID': 'c', 'Number': 3}]
一条建议:给定您的最终数据结构,我想知道现在将最终数据表示为字典是否会更好-用ID
作为键,因为它们现在是唯一的。这样可以更方便地访问数据。