Skip to main content
 首页 » 编程设计

python之检查字典列表是否包含值和返回键

2025年05月04日11youxin

我有一个包含一组键值对的字典,其中的值是一个列表,如下所示:

my_dict = {7: [6, 13], 6: [7, 8, 9, 11, 13, 14], 8: [6, 14], 9: [6], 11: [6], 13: [6, 7], 14: [6, 8]} 

我想检查哪些列表包含值“6”并返回与匹配项对应的键。 (即 7、8、9、11、13 和 14)

我试过下面的代码:

def find_key_for(input_dict, value):     
    for k, v in input_dict.items(): 
        if v == value: 
            yield k 
        else: 
            return "None" 
 
keys = list(find_key_for(my_dict, 6)) 

但它返回以下错误:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() 

如何解决此问题以返回列表中包含此值的所有键?谢谢

请您参考如下方法:

你可以使用dict.items():

my_dict = {7: [6, 13], 6: [7, 8, 9, 11, 13, 14], 8: [6, 14], 9: [6], 11: [6], 13: [6, 7], 14: [6, 8]} 
new_dict = [a for a, b in my_dict.items() if 6 in b] 

输出:

[7, 8, 9, 11, 13, 14]