Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python dict remove duplicate values by key's value?

A dict

dic = {
 1: 'a', 
 2: 'a', 
 3: 'b', 
 4: 'a', 
 5: 'c', 
 6: 'd', 
 7: 'd', 
 8: 'a', 
 9: 'a'}

I want to remove duplicate values just keep one K/V pair, Regarding the "key" selection of those duplicated values, it may be max or min or by random select one of those duplicated item's key.

I do not want to use a k/v swap since that can not control the key selection.

Take value "a" for example

 1: 'a', 
 2: 'a', 
 4: 'a', 
 8: 'a', 
 9: 'a'

the max key will be {9: 'a'} and the min will be {1: 'a'}, and the random will choise any one of it.

And, if the key is other kind of hashable value, for example, string, then how to do such a selection?

Can anyone share me an idea?

Thanks!

like image 556
K. C Avatar asked Jul 10 '26 19:07

K. C


1 Answers

You could build a reverse dictionary where the values are lists of all the keys from your initial dictionary. Using this you could then do what you want, min, max, random, alternate min and max, or whatever.

from collections import defaultdict

d = defaultdict(list)
for k,v in dic.iteritems():
    d[v].append(k)

print d
# {'a': [1, 2, 4, 8, 9], 'c': [5], 'b': [3], 'd': [6, 7]}
like image 101
tom10 Avatar answered Jul 12 '26 14:07

tom10



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!