Python - 列表和字典中的常用键
给定字典和列表,提取所有常见的键和列表。
Input : test_dict = {“Gfg”: 3, “is” : 5, “best” : 9, “for” : 0, “geeks” : 3}, test_list = [“Gfg”, “best”, “CS”]
Output : [‘Gfg’, ‘best’]
Explanation : Gfg and best are present in both dictionary and List.
Input : test_dict = {“Gfg”: 3, “is” : 5, “best” : 9, “for” : 0, “geeks” : 3}, test_list = [“Gfg”, “good”, “CS”]
Output : [‘Gfg’]
Explanation : Gfg is present in both dictionary and List.
方法#1:使用列表理解
这是可以执行此任务的方法之一。在此,我们迭代所有字典和列表值,如果找到匹配项,则将它们添加到结果中。
Python3
# Python3 code to demonstrate working of
# Common keys in list and dictionary
# Using list comprehension
# initializing dictionary
test_dict = {"Gfg": 3, "is" : 5, "best" : 9, "for" : 0, "geeks" : 3}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing test_list
test_list = ["Gfg", "best", "geeks"]
# using in operator to check for match
res = [ele for ele in test_dict if ele in test_list]
# printing result
print("The required result : " + str(res))
Python3
# Python3 code to demonstrate working of
# Common keys in list and dictionary
# Using set() + intersection()
# initializing dictionary
test_dict = {"Gfg": 3, "is" : 5, "best" : 9, "for" : 0, "geeks" : 3}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing test_list
test_list = ["Gfg", "best", "geeks"]
# intersection() used to get Common elements
res = set(test_list).intersection(set(test_dict))
# printing result
print("The required result : " + str(list(res)))
输出
The original dictionary is : {'Gfg': 3, 'is': 5, 'best': 9, 'for': 0, 'geeks': 3}
The required result : ['Gfg', 'best', 'geeks']
方法#2:使用set()+intersection()
这是可以执行此任务的另一种方式。在此,我们将容器、列表和字典键都转换为 set(),然后相交以找到所需的匹配项。
蟒蛇3
# Python3 code to demonstrate working of
# Common keys in list and dictionary
# Using set() + intersection()
# initializing dictionary
test_dict = {"Gfg": 3, "is" : 5, "best" : 9, "for" : 0, "geeks" : 3}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing test_list
test_list = ["Gfg", "best", "geeks"]
# intersection() used to get Common elements
res = set(test_list).intersection(set(test_dict))
# printing result
print("The required result : " + str(list(res)))
输出
The original dictionary is : {'Gfg': 3, 'is': 5, 'best': 9, 'for': 0, 'geeks': 3}
The required result : ['best', 'geeks', 'Gfg']