📜  Python – 删除具有 K 值的键

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

Python – 删除具有 K 值的键

给定一个字典,删除所有值等于 K 的键。

方法#1:使用字典理解

这是可以执行此任务的方式之一。在此,我们仅检查不等于 K 的元素并将其保留在字典理解中作为单行。

Python3
# Python3 code to demonstrate working of 
# Remove Keys with K value
# Using dictionary comprehension
  
# initializing dictionary
test_dict = {'Gfg' : 6, 'is' : 7, 'best' : 9, 'for' : 6, 'geeks' : 11} 
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# initializing K 
K = 6
  
# using dictionary comprehension 
# to compare not equal to K and retain 
res = {key: val for key, val in test_dict.items() if val != K}
          
# printing result 
print("The filtered dictionary : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Remove Keys with K value
# Using dict() + filter() + lambda
  
# initializing dictionary
test_dict = {'Gfg' : 6, 'is' : 7, 'best' : 9, 'for' : 6, 'geeks' : 11} 
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# initializing K 
K = 6
  
# employing lambda for computation 
# filter() to perform filter according to lambda
res = dict(filter(lambda key: key[1] != K, test_dict.items()))
          
# printing result 
print("The filtered dictionary : " + str(res))


输出
The original dictionary is : {'Gfg': 6, 'is': 7, 'best': 9, 'for': 6, 'geeks': 11}
The filtered dictionary : {'is': 7, 'best': 9, 'geeks': 11}

方法 #2:使用 dict() + filter() + lambda

上述功能的组合可以用来解决这个问题。在此,我们过滤所有非 K 元素并保留。最后使用 dict() 将结果转换为字典。

Python3

# Python3 code to demonstrate working of 
# Remove Keys with K value
# Using dict() + filter() + lambda
  
# initializing dictionary
test_dict = {'Gfg' : 6, 'is' : 7, 'best' : 9, 'for' : 6, 'geeks' : 11} 
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# initializing K 
K = 6
  
# employing lambda for computation 
# filter() to perform filter according to lambda
res = dict(filter(lambda key: key[1] != K, test_dict.items()))
          
# printing result 
print("The filtered dictionary : " + str(res)) 
输出
The original dictionary is : {'Gfg': 6, 'is': 7, 'best': 9, 'for': 6, 'geeks': 11}
The filtered dictionary : {'is': 7, 'best': 9, 'geeks': 11}