How to uniquely dictate by value?

I want unique duplicate values ​​in a dict. It looks like this:

d = {
"a":1,
"b":2,
"c":2,
"d":3,
"e":4,
"f":5,
"g":1,
"h":2,
"i":2,
"j":1,
"k":1}

Here is what I did:

# sort and unique the dict values
obj = d.values()
K = []
K = sorted(list(zip(*[(x,K.append(x)) for x in obj if not x in K])[0]

V=[]
for v1 in L:  
     V.append([k for k, v in obj.iteritems() if v == v1][0])
d_out = dict(zip(K, V))  

1. So, will K, V be in the correct order? Also, it can be a bit complicated, can anyone give a simple solution for the unique dict value over them?

2. Is it possible to do the following:

for v1 in L:  
     V.append([k for k, v in obj.iteritems() if v == v1][0])

This does not work on my testing:

[V.append([k for k, v in obj.iteritems() if v == v1][0]) for v1 in L] 

3. I realized that I can use the value of the exchange key to achieve this (a unique dict value by its value), but I have no idea how to select the key when the swap caused a conflict with this key:

dict((value, key) for key, value in my_dict.iteritems())  

, , , , . , ? -, dict?

4. "" python dict, , , , python dict?

+3
3
  • . .

  • .

  • dict " ". , .

  • , .

dupe . , , , dict.

d = {
    "a":1,
    "b":2,
    "c":2,
    "d":3,
    "e":4,
    "f":5,
    "g":1,
    "h":2,
    "i":2,
    "j":1,
    "k":1}

# Extract the dictionary into a list of (key, value) tuples.
t =  [(k, d[k]) for k in d]

# Sort the list -- by default it will sort by the key since it is
# first in the tuple.
t.sort()

# Reset the dictionary so it is ready to hold the new dataset.
d = {}

# Load key-values into the dictionary. Only the first value will be
# stored.
for k, v in t:
    if v in d.values():
        continue
    d[k] = v

print d
+3
try it out:

from collections import defaultdict
dout = defaultdict(dict)
for k,v in d.iteritems():
    dout[v] = k 
dout = dict(dout)
fdict = dict(zip(dout.values(), dout.keys()))

N.B: , ,

+2

Perhaps this will help:

import collections

d = ... # like above
d1 = collections.defaultdict(list)

for k, v in d.iteritems():
    d1[v].append(k)

print d1
+1
source

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


All Articles