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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With