haa*_*agn 1 python dictionary key-value
我有一个字典,其中包含一组键:值对,其中值是这样的列表:
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)
如何解决此问题以返回列表中包含此值的所有键?谢谢
你可以使用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]
Run Code Online (Sandbox Code Playgroud)
输出:
[7, 8, 9, 11, 13, 14]
Run Code Online (Sandbox Code Playgroud)