Get key by value in dictionary with same value in python?

Assume the dictionary

d={'a':1,'b':2,'c':1}

When i use

d.keys()[d.values(). index(1)]

I receive 'a', but I want to receive 'c', since the value 'c'is 1. How can I do this?

+4
source share
3 answers

You can use list comprehension like

print [key for key in d if d[key] == 1]

It iterates through the keys of the dictionary and checks if it matters 1. If the value is 1, it adds the corresponding list to the list.

Alternatively, you can use dict.iteritems()in Python 2.7, for example

print [key for key, value in d.iteritems() if value == 1]

In Python 3.x, you would do the same with dict.items(),

print([key for key, value in d.items() if value == 1])
+10
source

, - . , , " ":

from collections import defaultdict
def reverse(d):
     r = defaultdict(list)
     for k, v in d.items():
         r[v].append(k)
     return r

d={'a':1,'b':2,'c':1}
index = reverse(d)
print index[1]  
=> ['a', 'c']
print index[2]
=> ['b']
+2

, dict, .

d={'a':1,'b':2,'c':1}
x = filter(lambda k: d[k]==1, d.keys())
print x
['a', 'c']

I do not know if it is more efficient than a manual cycle; probably no. But it is more compact and understandable.

+1
source

All Articles