-2

I have a list of dicts like this:

[{'ID': 'a', 'Number': 2}, {'ID': 'b', 'Number': 5} , {'ID': 'a', 'Number': 6}, {'ID': 'a', 'Number': 8}, {'ID': 'c', 'Number': 3}]

I want to remove the dicts that have same key and only keep the one with smallest value. The expected result should be:

[{'ID': 'a', 'Number': 2}, {'Id': 'b', 'Number': 5}, {'ID': 'c', 'Number': 3}]

1 Answers1

1

Most efficient solution would be to use a temporary lookup dictionary with keys as IDs and values as the current dict which has the lowest Number corresponding to that 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())

which gives output as:

[{'ID': 'a', 'Number': 2}, {'ID': 'b', 'Number': 5}, {'ID': 'c', 'Number': 3}]

A piece of advice: given your final data structure, I wonder if you may be better off now representing this final data as a dictionary - with the IDs as keys since these are now unique. This would allow for more convenient data access.

Joe Iddon
  • 20,101
  • 7
  • 33
  • 54