import.zee import.zee - 1 year ago 92
Python Question

Find common values in dictionary that has keys with multiple values

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
in d and get the keys a, b and c or find
and get keys a and c.

Answer Source

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']
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download