Python – 大于 K 的过滤器和双键
有时,在使用Python字典时,我们可以同时完成操作和过滤后提取某些键的任务。这个问题也可以推广到其他值和操作。这在许多领域都有应用,例如日常编程和 Web 开发。让我们讨论可以执行此任务的某些方式。
方法#1:使用循环
这是解决此问题的一种方法。在此,我们采用蛮力的方式仅提取过滤后的元素并在将它们加倍后存储。
# Python3 code to demonstrate working of
# Filter and Double keys greater than K
# Using loop
# initializing dictionary
test_dict = {'Gfg' : 4, 'is' : 2, 'best': 3, 'for' : 6, 'geeks' : 1}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# initializing K
K = 2
# Filter and Double keys greater than K
# Using loop
res = dict()
for key, val in test_dict.items():
if val > K:
res[key] = val * 2
# printing result
print("The filtred dictionary : " + str(res))
输出 :
The original dictionary : {‘geeks’: 1, ‘for’: 6, ‘Gfg’: 4, ‘is’: 2, ‘best’: 3}
The filtred dictionary : {‘for’: 12, ‘Gfg’: 8, ‘best’: 6}
方法#2:使用字典理解
这是执行此任务的另一种方式。在此,我们以与上述方法类似的方式执行任务,但以更紧凑的方式。
# Python3 code to demonstrate working of
# Filter and Double keys greater than K
# Using dictionary comprehension
# initializing dictionary
test_dict = {'Gfg' : 4, 'is' : 2, 'best': 3, 'for' : 6, 'geeks' : 1}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# initializing K
K = 2
# Filter and Double keys greater than K
# Using dictionary comprehension
res = {key : val * 2 for key, val in test_dict.items() if val > K}
# printing result
print("The filtred dictionary : " + str(res))
输出 :
The original dictionary : {‘geeks’: 1, ‘for’: 6, ‘Gfg’: 4, ‘is’: 2, ‘best’: 3}
The filtred dictionary : {‘for’: 12, ‘Gfg’: 8, ‘best’: 6}