📜  Python – 删除值大于 K 的键(包括混合值)

📅  最后修改于: 2022-05-13 01:54:22.696000             🧑  作者: Mango

Python – 删除值大于 K 的键(包括混合值)

给定一个包含键值对的字典,删除所有值大于 K 的键,包括混合值。

方法 #1:使用 isinstance() + 循环

这是可以执行此任务的方式之一。在此,我们使用实例来获取整数值,并使用比较来获取不大于 K 的值。

Python3
# Python3 code to demonstrate working of 
# Remove keys with Values Greater than K ( Including mixed values )
# Using loop + isinstance()
  
# initializing dictionary
test_dict = {'Gfg' : 3, 'is' : 7, 'best' : 10, 'for' : 6, 'geeks' : 'CS'} 
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# initializing K 
K = 6
  
# using loop to iterate keys of dictionary
res = {}
for key in test_dict:
    
    # testing for data type and then condition, order is imp.
    if not (isinstance(test_dict[key], int) and test_dict[key] > K):
        res[key] = test_dict[key]
          
# printing result 
print("The constructed dictionary : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Remove keys with Values Greater than K ( Including mixed values )
# Using dictionary comprehension + isinstance()
  
# initializing dictionary
test_dict = {'Gfg' : 3, 'is' : 7, 'best' : 10, 'for' : 6, 'geeks' : 'CS'} 
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# initializing K 
K = 6
  
# using list comprehension to perform in one line
res = {key : val for key, val in test_dict.items() if not (isinstance(val, int) and (val > K))}
          
# printing result 
print("The constructed dictionary : " + str(res))


输出
The original dictionary is : {'Gfg': 3, 'is': 7, 'best': 10, 'for': 6, 'geeks': 'CS'}
The constructed dictionary : {'Gfg': 3, 'for': 6, 'geeks': 'CS'}

方法 #2:使用字典理解 + isinstance()

以上功能的组合就是用来解决这个问题的。这执行类似于上述方法的任务。唯一的区别是它使用字典理解在一个班轮中执行。

Python3

# Python3 code to demonstrate working of 
# Remove keys with Values Greater than K ( Including mixed values )
# Using dictionary comprehension + isinstance()
  
# initializing dictionary
test_dict = {'Gfg' : 3, 'is' : 7, 'best' : 10, 'for' : 6, 'geeks' : 'CS'} 
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# initializing K 
K = 6
  
# using list comprehension to perform in one line
res = {key : val for key, val in test_dict.items() if not (isinstance(val, int) and (val > K))}
          
# printing result 
print("The constructed dictionary : " + str(res)) 
输出
The original dictionary is : {'Gfg': 3, 'is': 7, 'best': 10, 'for': 6, 'geeks': 'CS'}
The constructed dictionary : {'Gfg': 3, 'for': 6, 'geeks': 'CS'}