4

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?

3 Answers 3

10

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])
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.