user3805063
user3805063

Reputation: 21

Getting Keys Using Unique Values in Dictionary

I have a code like this.When i'm executing this it prints only 'hello' but i want both. I want to print both keys in my dictionary because i'm passing here unique value can any one help me.

mydict = {'hai': 35, 'hello': 35}
print mydict.keys()[mydict.values().index(35)]

Upvotes: 0

Views: 74

Answers (2)

wwsatan
wwsatan

Reputation: 1

mydict = {'hai':35,'hello':35}
a=[]
for k, v in mydict.iteritems():
    if v == 35:
        a.append(k)

print a

Upvotes: 0

Tim Pietzcker
Tim Pietzcker

Reputation: 336118

index() only returns the first match by design. The best solution is probably a list comprehension:

>>> keys = [key for key,value in mydict.iteritems() if value==35]
>>> keys
['hello', 'hai']

Upvotes: 5

Related Questions