Reputation: 995
I am new to python and I have a problem. I am trying to find keys with a value; however, the keys have multiple values.
d = {
'a': ['john', 'doe', 'jane'],
'b': ['james', 'danny', 'john'],
'C':['john', 'scott', 'jane'],
}
I want to find the value john
in d and get the keys a, b and c or find jane
and get keys a and c.
Upvotes: 1
Views: 3810
Reputation: 109
So you have to go through the dictionary items and if the find keyword is in the item list then the corresponding key has to be stored in a list and this list has to be displayed.
d = {'a':['john', 'doe', 'jane'], 'b': ['james', 'danny', 'john'], 'C':['john', 'scott', 'jane'],}
find ='jane'
So this is how the logic is written in python
print ([m for m in d.keys() if find in d[m]])
And it will give the following output
['a', 'C']
Upvotes: 1
Reputation: 3341
This can easily be done using a list comprehension. It iterates over every key/value pair from the dict's items list, which contains all key/value pairs (for key,val in d.items()
) and selects only the pairs where the target string is contained in the value list (if 'john' in val
), building a list out of the resulting keys ([ key ... ]
).
>>> [ key for key,val in d.items() if 'john' in val ]
['b', 'a', 'C']
>>> [ key for key,val in d.items() if 'jane' in val ]
['a', 'C']
Upvotes: 2