Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 627
user3457749 Avatar asked Dec 11 '22 04:12

user3457749


2 Answers

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])
like image 111
thefourtheye Avatar answered Jan 18 '23 22:01

thefourtheye


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']
like image 28
bruno desthuilliers Avatar answered Jan 19 '23 00:01

bruno desthuilliers