Python dict remove duplicate values ​​by key 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 save one K / V pair. As for the “key” selection of these duplicate values, it can be max or min or randomly select one of these duplicate element keys.

I do not want to use k / v swap since it cannot control the key selection.

Take the value "a", for example

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

the maximum key will be {9: 'a'}, and min will be {1: 'a'}, and random will choose any of them.

And if the key is another value of the hashed value, for example, a string, then how to make such a choice?

Can anyone share an idea?

Thank!

+3
3
import itertools as it

newdic = {}
for v, grp in it.groupby(sorted((v, k) for k, v in dic.items)):
  newdic[min(k for _, k in grp)] = v

"" min (, , , - " " ).

, , - , , (, Python 3, - ), key= min ; -).

+2

, . , , , min, max, random, alternate min max - .

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]}
+5

:

In [29]: dic
Out[29]: {1: 'a', 2: 'a', 3: 'b', 4: 'a', 5: 'c', 6: 'd', 7: 'd', 8: 'a', 9: 'a'}

In [30]: dict((v,k) for k,v in dic.iteritems())
Out[30]: {'a': 9, 'b': 3, 'c': 5, 'd': 7}

In [31]: dict((v,k) for k,v in dict((v,k) for k,v in dic.iteritems()).iteritems())
Out[31]: {3: 'b', 5: 'c', 7: 'd', 9: 'a'}
+1

Source: https://habr.com/ru/post/1757936/


All Articles