简体   繁体   中英

Return dictionary key containing two specific values

I come today with a rather simple problem. I have a dictionary with keys containing a list of elements. I know how to return the key if it contains one specific value but how can I do it if I am looking for two specific values together?

Let's suppose I have a dict called my_dict, with keys (0 to 10) and list of words for each key.

Ex:

my_dict = {
    0 : ['bear', 'tiger', 'lion'], 
    1: ['cheetah', 'tiger', 'snake'], 
    2: ['bear', 'tiger', 'elephant'], 
    # and so on...
}

I want to return the keys for which I have the words bear and tiger together :)

Thank you in advance

You could iterate and do a simple check

>>> my_dict = {0 : ['bear', 'tiger', 'lion'], 1: ['cheetah', 'tiger', 'snake'], 2: ['bear', 'tiger', 'elephant']}
>>>
>>> [x for x,y in my_dict.items() if 'bear' in y and 'tiger' in y]
[0, 2]

Try this

my_dict = {0 : ['bear', 'tiger', 'lion'], 1: ['cheetah', 'tiger', 'snake'], 2: ['bear', 'tiger', 'elephant']}
keys = []
for k,v in my_dict.items():
    if 'bear' in v and 'tiger' in v:
        keys.append(k)
print(keys)  # [0, 2]

iterate the dictionary using items function, check the existence of value 1 then value 2 in dictionary list value if found return the key. Below is example code which can be customised based on need:

my_dict = {101 : ['bear', 'tiger', 'lion'], 100: ['cheetah', 'tiger', 'snake'], 102: ['bear', 'tiger', 'elephant']}
def get_dict_key(val1,val2):
    for k,v in my_dict.items():
        if val1 in v:
            if val2 in v:
                return k

get_dict_key('cheetah','tiger')

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