Python - 使用 K 键删除具有匹配值的字典
给定两个字典列表,从其他字典列表中删除所有具有相似 K 键值的字典。
Input : test_list = [{‘Gfg’ : 3, “is” : 3, “best” : 9},
{‘Gfg’ : 8, “is” : 4, “best” : 2},
{‘Gfg’ : 9, “is” : 2, “best” : 4},
{‘Gfg’ : 8, “is” : 10, “best” : 3},
{‘Gfg’ : 7, “is” : 1, “best” : 7}], check_list = [{‘Gfg’ : 8, “Best” : 1}, {“Best” : 2, “Gfg” : 7}], K = “Gfg”
Output : [{‘Gfg’: 3, ‘is’: 3, ‘best’: 9}, {‘Gfg’: 9, ‘is’: 10, ‘best’: 3}]
Explanation : All dictionaries with “Gfg”‘s value as 8 or 7 is removed.
Input : test_list = [{‘Gfg’ : 3, “is” : 3, “best” : 9},
{‘Gfg’ : 8, “is” : 4, “best” : 2}], check_list = [{‘Gfg’ : 8, “Best” : 1}, {“Best” : 2, “Gfg” : 7}], K = “Gfg”
Output : [{‘Gfg’: 3, ‘is’: 3, ‘best’: 9}]
Explanation : All dictionaries with “Gfg”‘s value as 8 or 7 is removed.
方法:使用列表理解+字典理解
在这种情况下,我们使用字典理解来执行获取一组元素的任务,然后使用列表理解通过测试 K 键值在构造的值集中的缺失来构建新列表。
整个任务分两步进行,
- 使用set()从与键K对应的check_list中提取所有唯一值。
- 检查测试列表中的每个字典的键K的值,如果它存在于第一步创建的集合中,则结果中将省略该字典,否则将添加字典作为结果。
Python3
# Python3 code to demonstrate working of
# Remove Dictionaries with Matching Values with K Key
# Using dictionary comprehension + list comprehension
# initializing list
test_list = [{'Gfg': 3, "is": 3, "best": 9},
{'Gfg': 8, "is": 4, "best": 2},
{'Gfg': 1, "is": 2, "best": 4},
{'Gfg': 9, "is": 10, "best": 3},
{'Gfg': 7, "is": 1, "best": 7}]
# printing original list
print("The original list is : " + str(test_list))
# initializing check dictionary list
check_list = [{'Gfg': 8, "Best": 1}, {"Best": 2, "Gfg": 7}]
# initializing Key
K = "Gfg"
# getting set of values
temp = {sub[K] for sub in check_list}
# checking for value occurrence in test dictionary using in
# filtering only with no matching values
res = [sub for sub in test_list if sub[K] not in temp]
# printing result
print("Dictionary list after removal : " + str(res))
输出:
The original list is : [{‘Gfg’: 3, ‘is’: 3, ‘best’: 9}, {‘Gfg’: 8, ‘is’: 4, ‘best’: 2}, {‘Gfg’: 1, ‘is’: 2, ‘best’: 4}, {‘Gfg’: 9, ‘is’: 10, ‘best’: 3}, {‘Gfg’: 7, ‘is’: 1, ‘best’: 7}]
Dictionary list after removal : [{‘Gfg’: 3, ‘is’: 3, ‘best’: 9}, {‘Gfg’: 1, ‘is’: 2, ‘best’: 4}, {‘Gfg’: 9, ‘is’: 10, ‘best’: 3}]