user3457749
user3457749

Reputation: 1043

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

Assume a dictionary

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

When I use

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

I get 'a',but i want get 'c' as well ,since the value of 'c' is also 1. How can i do that?

Upvotes: 4

Views: 630

Answers (3)

rblandau
rblandau

Reputation: 11

You can use the filter function to see all the keys in the dict that have the value you want.

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

I don't know if it is any more efficient than the manual loop; probably not. But it's more compact and clearer.

Upvotes: 1

bruno desthuilliers
bruno desthuilliers

Reputation: 77892

For a one-shot, thefourtheye's answer is the most obvious and straightforward solution. Now if you need to lookup more than one value, you may want to build a "reverse index" instead:

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']

Upvotes: 2

thefourtheye
thefourtheye

Reputation: 239443

You can use list comprehension, like this

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

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

Alternatively you can use, dict.iteritems() in Python 2.7, like this

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])

Upvotes: 10

Related Questions