简体   繁体   中英

Find dictionary key using value from list

i'm trying to find a element in a list and return the the key who has that list. Example:

mydict = {'hi':[1,2], 'hello':[3,4]}

print(find(1))
return 'hi

Is there any simple way to do it?

This function will return all the keys that contain the given value as a list.

def find(to_find, inp_dct):
    return [i for i in inp_dct if to_find in inp_dct[i]] 
for k in mydict:
    if val in mydict[k]:
        print(k)

Where val is the value you want to find.

You can simply loop through your dictionary as key,value pairs and your search value is in values list, it will return the value.

Code:

mydict = {'hi':[1,2], 'hello':[3,4]}

def find(item):
    for key, value in mydict.items():
        if item in value:
            return key
        
print(find(1))

Output: hi

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