views:

44

answers:

2

Hi, this question might have similars in SO but my case is a bit different. and I tried to adapt those answers to my problem but couldn't. so here is the thing: I have this list :

[(['c', 'a', 'b'], 10), (['c', 'a', 'b'], 9),(['h','b'],2)] for example.

I want to remove the duplicates in this list by keeping tuple that has the larger number associated with it. so the list should look like this:

[(['c', 'a', 'b'], 10),(['h','b'],2)]

can anyone help me? the order of the items inside the inner lists is very important. thanks

+2  A: 
>>> lst = [(['c', 'a', 'b'], 10), (['c', 'a', 'b'], 9),(['h','b'],2)]
>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> for i, j in lst:
    d[tuple(i)] = max(d[tuple(i)], j)          # assuming positive numbers


>>> d
defaultdict(<class 'int'>, {('h', 'b'): 2, ('c', 'a', 'b'): 10})
SilentGhost
You can then just do `list(d.iteritems())` to get back to a list.
Space_C0wb0y
+1  A: 

If, as your example suggests, the items are already sorted by the numbers (in your case reverse), you can do:

d = dict(reversed(lst))
list(d.iteritems())

The default behavior of the dict() function is that the last seen value for the key is stored. So if they are sorted in reverse order, the last seen value when iterating in reverse order will be the largest. Otherwise, use @SilentGhost`s answer.

Space_C0wb0y