Python - 如果不存在特定值,则从字典列表中删除字典
给定一个字典列表,删除所有没有 K 作为值的字典。
例子:
Input : test_list = [{“Gfg” : 4, “is” : 8, “best” : 9}, {“Gfg” : 3, “is”: 7, “best” : 5}], K = 7
Output : [{‘Gfg’: 4, ‘is’: 8, ‘best’: 9}]
Explanation : Resultant dictionary doesn’t contain 7 as any element.
Input : test_list = [{“Gfg” : 4, “is” : 7, “best” : 9}, {“Gfg” : 3, “is”: 7, “best” : 5}], K = 7
Output : []
Explanation : All contain 7 as element in List.
方法 #1:使用循环 + values()
这是可以执行此任务的方法之一。在这种情况下,我们使用循环执行迭代所有字典的任务,并使用 values() 检查值的存在。
Python3
# Python3 code to demonstrate working of
# Remove dictionary if K value not present
# Using loop + values()
# initializing lists
test_list = [{"Gfg" : 4, "is" : 8, "best" : 9},
{"Gfg" : 5, "is": 8, "best" : 1},
{"Gfg" : 3, "is": 7, "best" : 6},
{"Gfg" : 3, "is": 7, "best" : 5}]
# printing original list
print("The original list : " + str(test_list))
# initializing K
K = 7
res = []
# using loop to check for K element
for sub in test_list:
if K not in list(sub.values()):
res.append(sub)
# printing result
print("Filtered dictionaries : " + str(res))
Python3
# Python3 code to demonstrate working of
# Remove dictionary if K value not present
# Using list comprehension
# initializing lists
test_list = [{"Gfg" : 4, "is" : 8, "best" : 9},
{"Gfg" : 5, "is": 8, "best" : 1},
{"Gfg" : 3, "is": 7, "best" : 6},
{"Gfg" : 3, "is": 7, "best" : 5}]
# printing original list
print("The original list : " + str(test_list))
# initializing K
K = 7
res = []
# using one-liner to extract dicts with NO K value
# using not in operator to check presence
res = [sub for sub in test_list if K not in list(sub.values())]
# printing result
print("Filtered dictionaries : " + str(res))
输出:
The original list : [{‘Gfg’: 4, ‘is’: 8, ‘best’: 9}, {‘Gfg’: 5, ‘is’: 8, ‘best’: 1}, {‘Gfg’: 3, ‘is’: 7, ‘best’: 6}, {‘Gfg’: 3, ‘is’: 7, ‘best’: 5}]
Filtered dictionaries : [{‘Gfg’: 4, ‘is’: 8, ‘best’: 9}, {‘Gfg’: 5, ‘is’: 8, ‘best’: 1}]
方法#2:使用列表理解
这是可以执行此任务的另一种方式。在这里,我们使用列表理解使用单行提取所有值。使用 values() 提取值。
蟒蛇3
# Python3 code to demonstrate working of
# Remove dictionary if K value not present
# Using list comprehension
# initializing lists
test_list = [{"Gfg" : 4, "is" : 8, "best" : 9},
{"Gfg" : 5, "is": 8, "best" : 1},
{"Gfg" : 3, "is": 7, "best" : 6},
{"Gfg" : 3, "is": 7, "best" : 5}]
# printing original list
print("The original list : " + str(test_list))
# initializing K
K = 7
res = []
# using one-liner to extract dicts with NO K value
# using not in operator to check presence
res = [sub for sub in test_list if K not in list(sub.values())]
# printing result
print("Filtered dictionaries : " + str(res))
输出:
The original list : [{‘Gfg’: 4, ‘is’: 8, ‘best’: 9}, {‘Gfg’: 5, ‘is’: 8, ‘best’: 1}, {‘Gfg’: 3, ‘is’: 7, ‘best’: 6}, {‘Gfg’: 3, ‘is’: 7, ‘best’: 5}]
Filtered dictionaries : [{‘Gfg’: 4, ‘is’: 8, ‘best’: 9}, {‘Gfg’: 5, ‘is’: 8, ‘best’: 1}]