Python – 值范围内的字典项
给定一个值范围,提取其键位于值范围内的所有项目。
Input : {‘Gfg’ : 6, ‘is’ : 7, ‘best’ : 9, ‘for’ : 8, ‘geeks’ : 11}, i, j = 9, 12
Output : {‘best’ : 9, ‘geeks’ : 11}
Explanation : Keys within 9 and 11 range extracted.
Input : {‘Gfg’ : 6, ‘is’ : 7, ‘best’ : 9, ‘for’ : 8, ‘geeks’ : 11}, i, j = 14, 18
Output : {}
Explanation : No values in range.
方法#1:使用循环
这是可以执行此任务的粗暴方式。在此,我们对所有键运行一个循环,并对值范围进行条件检查。
Python3
# Python3 code to demonstrate working of
# Dictionary items in value range
# Using loop
# initializing dictionary
test_dict = {'Gfg' : 6, 'is' : 7, 'best' : 9, 'for' : 8, 'geeks' : 11}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing range
i, j = 8, 12
# using loop to iterate through all keys
res = dict()
for key, val in test_dict.items():
if int(val) >= i and int(val) <= j:
res[key] = val
# printing result
print("The extracted dictionary : " + str(res))
Python3
# Python3 code to demonstrate working of
# Dictionary items in value range
# Using filter() + lambda + dictionary comprehension
# initializing dictionary
test_dict = {'Gfg' : 6, 'is' : 7, 'best' : 9, 'for' : 8, 'geeks' : 11}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing range
i, j = 8, 12
# using dictionary comprehension to compile result in one
res = {key: val for key, val in filter(lambda sub: int(sub[1]) >= i and
int(sub[1]) <= j, test_dict.items())}
# printing result
print("The extracted dictionary : " + str(res))
输出
The original dictionary is : {'Gfg': 6, 'is': 7, 'best': 9, 'for': 8, 'geeks': 11}
The extracted dictionary : {'best': 9, 'for': 8, 'geeks': 11}
方法 #2:使用 filter() + lambda + 字典理解
上述功能的组合可以用来解决这个问题。在此,我们使用 filter() 执行过滤任务,并且 lambda 用于条件检查。
Python3
# Python3 code to demonstrate working of
# Dictionary items in value range
# Using filter() + lambda + dictionary comprehension
# initializing dictionary
test_dict = {'Gfg' : 6, 'is' : 7, 'best' : 9, 'for' : 8, 'geeks' : 11}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing range
i, j = 8, 12
# using dictionary comprehension to compile result in one
res = {key: val for key, val in filter(lambda sub: int(sub[1]) >= i and
int(sub[1]) <= j, test_dict.items())}
# printing result
print("The extracted dictionary : " + str(res))
输出
The original dictionary is : {'Gfg': 6, 'is': 7, 'best': 9, 'for': 8, 'geeks': 11}
The extracted dictionary : {'best': 9, 'for': 8, 'geeks': 11}