+2 votes
in Programming Languages by (14.4k points)
I have a dictionary with values as sets. I want to find the key whose value contains a particular value.

e.g.  aa={'a':set([5,6,7]),'b':set([1,2]),'1':set(['c','v']),'2':set(['y','m'])}

If I am want to find the key with value containing 'm', it should return 2.

1 Answer

+1 vote
by (22.9k points)
edited by

Try out one of the following approaches. There can be other approaches.

Python 2

>>> aa={'a':set([5,6,7]),'b':set([1,2]),'1':set(['c','v']),'2':set(['y','m'])}
Approach 1
>>> for i in range(len(aa.keys())):
...     if 'm' in aa.values()[i]:
...             print(aa.keys()[i])
...             break

Approach 2: Pythonic way in 1 line
>>> aa.keys()[[i for i in range(len(aa.values())) if 'm' in aa.values()[i]][0]]


>>> list(aa.keys())[[i for i in range(len(aa.values())) if 'm' in list(aa.values())[i]][0]]

If the values are not sets, you can do the following:


>>> tt={'a':5,'b':1}
>>> tt.keys()[tt.values().index(1)]


>>> list(tt.keys())[list(tt.values()).index(1)]