📜  Python|从字典中删除以 K 开头的键

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

Python|从字典中删除以 K 开头的键

有时,在使用字典时,我们可能会遇到需要删除某些键的特定用例。我们可能需要根据许多标准来执行此任务。一个这样的标准可以是基于起始子字符串的删除。让我们讨论可以执行此任务的某些方式。

方法#1:使用朴素方法+ startswith() + pop()
可以使用上述功能的组合来执行此特定任务,这是执行此任务的蛮力方法。 pop函数用于删除键值对并startswith提供必须执行此操作的条件。

# Python3 code to demonstrate working of
# Remove Keys from dictionary starting with K
# Using Naive Method + startswith() + pop()
  
# initializing dictionary
test_dict = {"Apple" : 1, "Star" : 2, "App" : 4, "Gfg" : 3}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# initializing Substring 
K = "Ap"
  
# Using Naive Method + startswith() + pop()
# Remove Keys from dictionary starting with K
res = list(test_dict.keys())
for key in res:
  if key.startswith(K):
    test_dict.pop(key)
  
# printing result 
print("Dictionary after key removal : " + str(test_dict))
输出 :
The original dictionary is : {'Apple': 1, 'Star': 2, 'App': 4, 'Gfg': 3}
Dictionary after key removal : {'Star': 2, 'Gfg': 3}

方法 #2:使用列表理解 + dict() + startswith() + items()
还有一种替代方案来执行此特定任务,其中我们使用items()获取所有键和值,然后使用不以 K 开头的键重建字典,使用startswith函数。最后的dict函数执行从列表到字典的转换。

# Python3 code to demonstrate working of
# Remove Keys from dictionary starting with K
# Using list comprehension + dict() + startswith() + items()
  
# initializing dictionary
test_dict = {"Apple" : 1, "Star" : 2, "App" : 4, "Gfg" : 3}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# initializing Substring 
K = "Ap"
  
# Using list comprehension + dict() + startswith() + items()
# Remove Keys from dictionary starting with K
res = dict( [(x, y) for x, y in test_dict.items() if not x.startswith(K)] )
  
# printing result 
print("Dictionary after key removal : " + str(res))
输出 :
The original dictionary is : {'Apple': 1, 'Star': 2, 'App': 4, 'Gfg': 3}
Dictionary after key removal : {'Star': 2, 'Gfg': 3}