用于提取自定义值的字典项的Python程序
给定字典,提取列表中与给定值匹配的所有项目
例子:
Input : test_dict = {“Gfg” : 3, “is” : 5, “for” : 8, “Geeks” : 10, “Best” : 16 }, sub_list = [5, 4, 10, 20, 16, 8]
Output : {‘is’: 5, ‘Geeks’: 10, ‘Best’: 16, “for” : 8}
Explanation : All values matching list values extracted along with keys.
Input : test_dict = {“Gfg” : 3, “is” : 5, “for” : 8, “Geeks” : 10, “Best” : 16 }, sub_list = [5, 4, 10]
Output : {‘is’: 5, ‘Geeks’: 10}
Explanation : All values matching list values extracted along with keys.
方法一:使用循环
使用“for 循环”是执行此任务的方法之一。在此,我们迭代所有键并检查该值是否存在于自定义列表中,如果是,则返回它。
Python3
# initializing dictionary
test_dict = {"Gfg": 3, "is": 5, "for": 8,
"Geeks": 10, "Best": 16}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing list
sub_list = [5, 4, 10, 20, 16]
# Using loop to perform iteration
res = dict()
for key in test_dict:
if test_dict[key] in sub_list:
res[key] = test_dict[key]
# printing result
print("Extracted items : " + str(res))
Python3
# initializing dictionary
test_dict = {"Gfg": 3, "is": 5, "for": 8,
"Geeks": 10, "Best": 16}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing list
sub_list = [5, 4, 10, 20, 16]
# dictionary comprehension to compile logic in one dictionary
# in operator used to check value existance
res = {key: val for key, val in test_dict.items() if val in sub_list}
# printing result
print("Extracted items : " + str(res))
输出:
The original dictionary is : {‘Gfg’: 3, ‘is’: 5, ‘for’: 8, ‘Geeks’: 10, ‘Best’: 16}
Extracted items : {‘is’: 5, ‘Geeks’: 10, ‘Best’: 16}
方法二:使用字典理解
这是一个单线,借助它可以执行此任务。在这种情况下,我们使用单行方法中的字典理解来迭代所有键。
蟒蛇3
# initializing dictionary
test_dict = {"Gfg": 3, "is": 5, "for": 8,
"Geeks": 10, "Best": 16}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing list
sub_list = [5, 4, 10, 20, 16]
# dictionary comprehension to compile logic in one dictionary
# in operator used to check value existance
res = {key: val for key, val in test_dict.items() if val in sub_list}
# printing result
print("Extracted items : " + str(res))
输出:
The original dictionary is : {‘Gfg’: 3, ‘is’: 5, ‘for’: 8, ‘Geeks’: 10, ‘Best’: 16}
Extracted items : {‘is’: 5, ‘Geeks’: 10, ‘Best’: 16}