Python – 删除以 Key 为特征的重复字典
给定一个字典列表,删除所有与 K 键重复的字典。
Input : test_list = [{“Gfg” : 6, “is” : 9, “best” : 10}, {“Gfg” : 8, “is” : 11, “best” : 10}, {“Gfg” : 2, “is” : 16, “best” : 10}], K = “best”
Output : [{“Gfg” : 6, “is” : 9, “best” : 10}]
Explanation : All keys have 10 value, only 1st record is retained.
Input : test_list = [{“Gfg” : 6, “is” : 9, “best” : 10}, {“Gfg” : 8, “is” : 11, “best” : 12}, {“Gfg” : 2, “is” : 16, “best” : 15}], K = “best”
Output : [{“Gfg” : 6, “is” : 9, “best” : 10}, {“Gfg” : 8, “is” : 11, “best” : 12}, {“Gfg” : 2, “is” : 16, “best” : 15}]
Explanation : All values of “best” are unique, hence no removal of dictionaries.
方法:使用循环
这是可以执行此任务的粗暴方式。在此,我们对每个字典进行迭代并记住键,如果出现相似键的相同值,则在结果字典列表中避免该字典。
Python3
# Python3 code to demonstrate working of
# Remove Duplicate Dictionaries characterized by Key
# Using loop
# initializing lists
test_list = [{"Gfg" : 6, "is" : 9, "best" : 10},
{"Gfg" : 8, "is" : 11, "best" : 19},
{"Gfg" : 2, "is" : 16, "best" : 10},
{"Gfg" : 12, "is" : 1, "best" : 8},
{"Gfg" : 22, "is" : 6, "best" : 8}]
# printing original list
print("The original list : " + str(test_list))
# initializing Key
K = "best"
memo = set()
res = []
for sub in test_list:
# testing for already present value
if sub[K] not in memo:
res.append(sub)
# adding in memo if new value
memo.add(sub[K])
# printing result
print("The filtered list : " + str(res))
The original list : [{‘Gfg’: 6, ‘is’: 9, ‘best’: 10}, {‘Gfg’: 8, ‘is’: 11, ‘best’: 19}, {‘Gfg’: 2, ‘is’: 16, ‘best’: 10}, {‘Gfg’: 12, ‘is’: 1, ‘best’: 8}, {‘Gfg’: 22, ‘is’: 6, ‘best’: 8}]
The filtered list : [{‘Gfg’: 6, ‘is’: 9, ‘best’: 10}, {‘Gfg’: 8, ‘is’: 11, ‘best’: 19}, {‘Gfg’: 12, ‘is’: 1, ‘best’: 8}]