简体   繁体   中英

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? Eg 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

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']}
>>>

Iterate over all the items in the dict

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

key_1 [23, 'ab', 'cd']

You can simply loop through your dictionary items and check if your value is in the value, eg:

for k, v in dict_a.items():  # use iteritems() on Python 2.x
    if "cd" in v:
        print("key: {}, value: {}".format(k, v))

You can write your own small method to check a value in the dictionary.

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

def checkValue(dictionary, value):
    for key, valueList in dict_a.items():
        if value in valueList:
            print("value(" + value + ") present in " + str(valueList) + " with key (" + key + ")")
            break

checkValue(dict_a, 'cd')

Sample Run

value(cd) present in [23, 'ab', 'cd'] with key (key_1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM