Python - 检查是否存在对应于 K 键的特定值
给定一个字典列表,检查特定的键值对是否存在。
Input : [{“Gfg” : “4”, “is” : “good”, “best” : “1”}, {“Gfg” : “9”, “is” : “CS”, “best” : “10”}], K = “Gfg”, val = “find”
Output : False
Explanation : No value of “Gfg” is “find”.
Input : [{“Gfg” : “4”, “is” : “good”, “best” : “1”}, {“Gfg” : “9”, “is” : “CS”, “best” : “10”}], K = “Gfg”, val = 4
Output : True
Explanation : 4 present as “Gfg” value.
方法#1:使用列表理解
这是可以执行此任务的方法之一。在这里,我们使用列表推导来提取字典,然后使用“in”运算符来检查它是否有任何值。
Python3
# Python3 code to demonstrate working of
# Check if particular value is present corresponding to K key
# Using list comprehension
# initializing lists
test_list = [{"Gfg" : "4", "is" : "good", "best" : "1"},
{"Gfg" : "find", "is" : "better", "best" : "8"},
{"Gfg" : "9", "is" : "CS", "best" : "10"}]
# printing original list
print("The original list : " + str(test_list))
# initializing K key
K = "Gfg"
# initializing target value
val = "find"
# extracting values using list comprehension
# using in operator to check for values
res = val in [sub[K] for sub in test_list]
# printing result
print("Is key-val pair present? : " + str(res))
Python3
# Python3 code to demonstrate working of
# Check if particular value is present corresponding to K key
# Using map() + in operator
# initializing lists
test_list = [{"Gfg" : "4", "is" : "good", "best" : "1"},
{"Gfg" : "find", "is" : "better", "best" : "8"},
{"Gfg" : "9", "is" : "CS", "best" : "10"}]
# printing original list
print("The original list : " + str(test_list))
# initializing K key
K = "Gfg"
# initializing target value
val = "find"
# extracting values using map
# using in operator to check for values
res = val in list(map(lambda sub : sub[K], test_list))
# printing result
print("Is key-val pair present? : " + str(res))
输出
The original list : [{'Gfg': '4', 'is': 'good', 'best': '1'}, {'Gfg': 'find', 'is': 'better', 'best': '8'}, {'Gfg': '9', 'is': 'CS', 'best': '10'}]
Is key-val pair present? : True
方法#2:使用 map() + in运算符
这是可以执行此任务的另一种方式。在这个获取与特定键对应的值的任务中,使用 map() 执行,将函数扩展到每个字典。
蟒蛇3
# Python3 code to demonstrate working of
# Check if particular value is present corresponding to K key
# Using map() + in operator
# initializing lists
test_list = [{"Gfg" : "4", "is" : "good", "best" : "1"},
{"Gfg" : "find", "is" : "better", "best" : "8"},
{"Gfg" : "9", "is" : "CS", "best" : "10"}]
# printing original list
print("The original list : " + str(test_list))
# initializing K key
K = "Gfg"
# initializing target value
val = "find"
# extracting values using map
# using in operator to check for values
res = val in list(map(lambda sub : sub[K], test_list))
# printing result
print("Is key-val pair present? : " + str(res))
输出
The original list : [{'Gfg': '4', 'is': 'good', 'best': '1'}, {'Gfg': 'find', 'is': 'better', 'best': '8'}, {'Gfg': '9', 'is': 'CS', 'best': '10'}]
Is key-val pair present? : True