Python – 如果键存在于列表和字典中,则提取键的值
给定一个列表、字典和一个键 K,如果键在列表和字典中都存在,则从字典中打印 K 的值。
Input : test_list = [“Gfg”, “is”, “Good”, “for”, “Geeks”], test_dict = {“Gfg” : 5, “Best” : 6}, K = “Gfg”
Output : 5
Explanation : “Gfg” is present in list and has value 5 in dictionary.
Input : test_list = [“Good”, “for”, “Geeks”], test_dict = {“Gfg” : 5, “Best” : 6}, K = “Gfg”
Output : None
Explanation : “Gfg” not present in List.
方法 #1:使用 all() + 生成器表达式
上述功能的组合提供了解决此问题的方法之一。在此我们使用 all() 来检查字典和列表中是否出现。如果结果为真值,则提取结果。
Python3
# Python3 code to demonstrate working of
# Extract Key's Value, if Key Present in List and Dictionary
# Using all() + list comprehension
# initializing list
test_list = ["Gfg", "is", "Good", "for", "Geeks"]
# initializing Dictionary
test_dict = {"Gfg" : 2, "is" : 4, "Best" : 6}
# initializing K
K = "Gfg"
# printing original list and Dictionary
print("The original list : " + str(test_list))
print("The original Dictionary : " + str(test_dict))
# using all() to check for occurrence in list and dict
# encapsulating list and dictionary keys in list
res = None
if all(K in sub for sub in [test_dict, test_list]):
res = test_dict[K]
# printing result
print("Extracted Value : " + str(res))
Python3
# Python3 code to demonstrate working of
# Extract Key's Value, if Key Present in List and Dictionary
# Using set() + intersection()
# initializing list
test_list = ["Gfg", "is", "Good", "for", "Geeks"]
# initializing Dictionary
test_dict = {"Gfg" : 2, "is" : 4, "Best" : 6}
# initializing K
K = "Gfg"
# printing original list and Dictionary
print("The original list : " + str(test_list))
print("The original Dictionary : " + str(test_dict))
# conversion of lists to set and intersection with keys
# using intersection
res = None
if K in set(test_list).intersection(test_dict):
res = test_dict[K]
# printing result
print("Extracted Value : " + str(res))
输出
The original list : ['Gfg', 'is', 'Good', 'for', 'Geeks']
The original Dictionary : {'Gfg': 2, 'is': 4, 'Best': 6}
Extracted Value : 2
方法#2:使用 set() + intersection()
这是检查两个容器中是否存在密钥的另一种方法。在此,我们计算 list 和 dict 键的所有值的交集,并在其中测试 Key 的出现。
Python3
# Python3 code to demonstrate working of
# Extract Key's Value, if Key Present in List and Dictionary
# Using set() + intersection()
# initializing list
test_list = ["Gfg", "is", "Good", "for", "Geeks"]
# initializing Dictionary
test_dict = {"Gfg" : 2, "is" : 4, "Best" : 6}
# initializing K
K = "Gfg"
# printing original list and Dictionary
print("The original list : " + str(test_list))
print("The original Dictionary : " + str(test_dict))
# conversion of lists to set and intersection with keys
# using intersection
res = None
if K in set(test_list).intersection(test_dict):
res = test_dict[K]
# printing result
print("Extracted Value : " + str(res))
输出
The original list : ['Gfg', 'is', 'Good', 'for', 'Geeks']
The original Dictionary : {'Gfg': 2, 'is': 4, 'Best': 6}
Extracted Value : 2