+2 votes
in Programming Languages by (73.6k 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

+2 votes
by (355k points)
selected by
 
Best answer

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
...
2

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

Python3

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

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

Python2

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

Python3

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


...