Python – 在异构字典中过滤字典值
有时,在使用Python字典时,我们可能会遇到一个问题,即我们需要根据特定类型的某些条件过滤掉某些值,例如所有小于 K 的值。当字典值可能是异构的时,这项任务变得复杂。这种问题可以在许多领域都有应用。让我们讨论可以执行此任务的某些方式。
Input : test_dict = {‘Gfg’ : 10, ‘for’ : ‘geeks’}
Output : {‘Gfg’: 10, ‘for’: ‘geeks’}
Input : test_dict = {‘Gfg’ : ‘geeks’}
Output : {‘Gfg’: ‘geeks’}
方法 #1:使用 type() + 字典理解
上述功能的组合可用于执行此任务。在此,我们使用 type() 检查整数类型并在字典理解中过滤数据。
Python3
# Python3 code to demonstrate working of
# Filter dictionary values in heterogeneous dictionary
# Using type() + dictionary comprehension
# initializing dictionary
test_dict = {'Gfg' : 4, 'is' : 2, 'best' : 3, 'for' : 'geeks'}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# initializing K
K = 3
# Filter dictionary values in heterogeneous dictionary
# Using type() + dictionary comprehension
res = {key : val for key, val in test_dict.items()
if type(val) != int or val > K}
# printing result
print("Values greater than K : " + str(res))
Python3
# Python3 code to demonstrate working of
# Filter dictionary values in heterogeneous dictionary
# Using isinstance() + dictionary comprehension
# initializing dictionary
test_dict = {'Gfg' : 4, 'is' : 2, 'best' : 3, 'for' : 'geeks'}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# initializing K
K = 3
# Filter dictionary values in heterogeneous dictionary
# Using isinstance() + dictionary comprehension
res = {key : val for key, val in test_dict.items()
if not isinstance(val, int) or val > K}
# printing result
print("Values greater than K : " + str(res))
输出 :
The original dictionary : {'Gfg': 4, 'for': 'geeks', 'is': 2, 'best': 3}
Values greater than K : {'Gfg': 4, 'for': 'geeks'}
方法 #2:使用 isinstance() + 字典理解
上述功能的组合也可以用来解决这个问题。在此,我们执行与上面类似的任务,但不同之处在于类型测试是由 isinstance() 而不是 type() 完成的。
Python3
# Python3 code to demonstrate working of
# Filter dictionary values in heterogeneous dictionary
# Using isinstance() + dictionary comprehension
# initializing dictionary
test_dict = {'Gfg' : 4, 'is' : 2, 'best' : 3, 'for' : 'geeks'}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# initializing K
K = 3
# Filter dictionary values in heterogeneous dictionary
# Using isinstance() + dictionary comprehension
res = {key : val for key, val in test_dict.items()
if not isinstance(val, int) or val > K}
# printing result
print("Values greater than K : " + str(res))
输出 :
The original dictionary : {'Gfg': 4, 'for': 'geeks', 'is': 2, 'best': 3}
Values greater than K : {'Gfg': 4, 'for': 'geeks'}