简体   繁体   中英

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?

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM