user308827 user308827 - 3 years ago 79
Python Question

Finding a key value pair in a dictionary that contains a specific value in python

In python 3 and python 2, is there a way to get the key value pair in a dictionary that contains a specific value? E.g. here is the dictionary:

dict_a = {'key_1': [23, 'ab', 'cd'], 'key_2': [12, 'aa', 'hg']}

How do I get the key value pair where 'cd' is present in the value? I tried using itervalues() but that does not seem to work

Answer Source

You can use a simple dictionary comprehension to check if cd is in the value of each key, value pair:

>>> dict_a = {'key_1': [23, 'ab', 'cd'], 'key_2': [12, 'aa', 'hg']}
>>> {k: v for k, v in dict_a.items() if 'cd' in v}
{'key_1': [23, 'ab', 'cd']}

This can be generalized by extracting the logic into a function:

>>> def filter_dict(d, key):
    return {k: v for k, v in d.items() if key in v}

>>> dict_a = {'key_1': [23, 'ab', 'cd'], 'key_2': [12, 'aa', 'hg']}
>>> filter_dict(dict_a, 'cd')
{'key_1': [23, 'ab', 'cd']}
>>>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download