简体   繁体   English

使用列表中的值查找字典键

[英]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.此 function 将返回包含给定值的所有键作为列表。

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.其中 val 是您要查找的值。

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 Output: hi

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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