📜  Python|从字典中删除多个键

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

Python|从字典中删除多个键

在使用Python字典时,我们可以使用需要一次删除多个键的实用程序。在使用 NoSQL 数据库的 Web 开发域中工作时可能会出现此类问题。让我们讨论可以执行此任务的某些方式。

方法 #1:使用pop() + 列表推导
在这个方法中,我们只使用了用于删除单个键的 pop函数以及迭代整个列表以执行删除操作的列表推导。

# Python3 code to demonstrate working of
# Remove multiple keys from dictionary
# Using pop() + list comprehension
  
# initializing dictionary
test_dict = {'Gfg' : 1, 'is' : 2, 'best' : 3, 'for' : 4, 'CS' : 5}
  
# initializing Remove keys
rem_list = ['is', 'for', 'CS']
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# Using pop() + list comprehension
# Remove multiple keys from dictionary
[test_dict.pop(key) for key in rem_list]
  
# printing result 
print("Dictionary after removal of keys : " + str(test_dict))
输出 :

方法 #2:使用items() + 列表理解 + dict()
在这种方法中,我们不是删除键,而是使用dict函数重建字典,使用items()提取键和值对并使用列表推导对其进行迭代。

# Python3 code to demonstrate working of
# Remove multiple keys from dictionary
# Using items() + list comprehension + dict()
  
# initializing dictionary
test_dict = {'Gfg' : 1, 'is' : 2, 'best' : 3, 'for' : 4, 'CS' : 5}
  
# initializing Remove keys
rem_list = ['is', 'for', 'CS']
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# Using items() + list comprehension + dict()
# Remove multiple keys from dictionary
res = dict([(key, val) for key, val in 
           test_dict.items() if key not in rem_list])
  
# printing result 
print("Dictionary after removal of keys : " + str(res))
输出 :