📜  Python – 如果键不存在则删除记录

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

Python – 如果键不存在则删除记录

有时,在使用Python字典时,我们可能会遇到一个问题,即我们需要删除所有不存在特定键的字典。这种问题可以在许多领域都有应用,例如日间编程和数据领域。让我们讨论可以执行此任务的某些方式。

方法 #1:使用列表推导
这是可以执行此任务的方式之一。在此,我们使用列表理解和条件语句迭代和测试关键存在。

Python3
# Python3 code to demonstrate working of
# Remove records if Key not present
# Using list comprehension
 
# initializing list
test_list = [{'Gfg' : 1, 'Best' : 3},
             {'Gfg' : 3, 'Best' : 5},
             {'Best' : 3}]
 
# printing original list
print("The original list : " + str(test_list))
 
# initializing K Key
K = 'Gfg'
 
# Remove records if Key not present
# Using list comprehension
res = [ele for ele in test_list if K in ele]
         
# printing result
print("List after filtration : " + str(res))


Python3
# Python3 code to demonstrate working of
# Remove records if Key not present
# Using list comprehension + keys()
 
# initializing list
test_list = [{'Gfg' : 1, 'Best' : 3},
             {'Gfg' : 3, 'Best' : 5},
             {'Best' : 3}]
 
# printing original list
print("The original list : " + str(test_list))
 
# initializing K Key
K = 'Gfg'
 
# Remove records if Key not present
# Using list comprehension + keys()
res = [ele for ele in test_list if K in ele.keys()]
         
# printing result
print("List after filtration : " + str(res))


输出 :
The original list : [{'Gfg': 1, 'Best': 3}, {'Gfg': 3, 'Best': 5}, {'Best': 3}]
List after filteration : [{'Gfg': 1, 'Best': 3}, {'Gfg': 3, 'Best': 5}]


方法 #2:使用列表理解 + 键()
上述功能的组合可以用来解决这个问题。在此,我们使用 keys() 执行提取所有键的任务,减少签入项目的开销。

Python3

# Python3 code to demonstrate working of
# Remove records if Key not present
# Using list comprehension + keys()
 
# initializing list
test_list = [{'Gfg' : 1, 'Best' : 3},
             {'Gfg' : 3, 'Best' : 5},
             {'Best' : 3}]
 
# printing original list
print("The original list : " + str(test_list))
 
# initializing K Key
K = 'Gfg'
 
# Remove records if Key not present
# Using list comprehension + keys()
res = [ele for ele in test_list if K in ele.keys()]
         
# printing result
print("List after filtration : " + str(res))
输出 :
The original list : [{'Gfg': 1, 'Best': 3}, {'Gfg': 3, 'Best': 5}, {'Best': 3}]
List after filteration : [{'Gfg': 1, 'Best': 3}, {'Gfg': 3, 'Best': 5}]