小编haa*_*agn的帖子

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

我有一个字典,其中包含一组键:值对,其中值是这样的列表:

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]}
Run Code Online (Sandbox Code Playgroud)

我想检查哪个列表包含值'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))
Run Code Online (Sandbox Code Playgroud)

但它返回以下错误:

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

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

python dictionary key-value

1
推荐指数
1
解决办法
2423
查看次数

标签 统计

dictionary ×1

key-value ×1

python ×1