Python – 检查字典值列表中的键
有时,在处理数据时,我们可能会遇到问题,我们收到一个字典,整个键具有字典列表作为值。在这种情况下,我们可能需要查找其中是否存在特定键。让我们讨论可以执行此任务的某些方式。
方法 #1:使用any()
这是执行此任务的简单且最推荐的方式。在这种情况下,我们只是通过迭代检查值中的键。
# Python3 code to demonstrate working of
# Check for Key in Dictionary Value list
# Using any()
# initializing dictionary
test_dict = {'Gfg' : [{'CS' : 5}, {'GATE' : 6}], 'for' : 2, 'CS' : 3}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing key
key = "GATE"
# Check for Key in Dictionary Value list
# Using any()
res = any(key in ele for ele in test_dict['Gfg'])
# printing result
print("Is key present in nested dictionary list ? : " + str(res))
输出 :
The original dictionary is : {'Gfg': [{'CS': 5}, {'GATE': 6}], 'for': 2, 'CS': 3}
Is key present in nested dictionary list ? : True
方法#2:使用列表理解 + in运算符
上述功能的组合可用于执行此任务。在此,我们使用理解遍历列表并执行键展平和存储键。然后我们使用 in运算符检查所需的密钥。
# Python3 code to demonstrate working of
# Check for Key in Dictionary Value list
# Using list comprehension + in operator
# initializing dictionary
test_dict = {'Gfg' : [{'CS' : 5}, {'GATE' : 6}], 'for' : 2, 'CS' : 3}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing key
key = "GATE"
# Check for Key in Dictionary Value list
# Using list comprehension + in operator
res = key in [sub for ele in test_dict['Gfg'] for sub in ele.keys()]
# printing result
print("Is key present in nested dictionary list ? : " + str(res))
输出 :
The original dictionary is : {'Gfg': [{'CS': 5}, {'GATE': 6}], 'for': 2, 'CS': 3}
Is key present in nested dictionary list ? : True