Python – 具有唯一值列表的字典
给定具有列表值的字典列表,提取唯一字典。
Input : [{‘Gfg’: [2, 3], ‘is’ : [7, 8], ‘best’ : [10]}, {‘Gfg’: [2, 3], ‘is’ : [7, 8], ‘best’ : [10]}]
Output : [{‘Gfg’: [2, 3], ‘is’: [7, 8], ‘best’: [10]}]
Explanation : Both are similar dictionaries, and hence 1 is removed.
Input : [{‘Gfg’: [2, 3], ‘is’ : [7, 8], ‘best’ : [10]}, {‘Gfg’: [2, 3], ‘is’ : [7, 8], ‘best’ : [10, 11]}]
Output : [{‘Gfg’: [2, 3], ‘is’: [7, 8], ‘best’: [10]}, {‘Gfg’: [2, 3], ‘is’: [7, 8], ‘best’: [10, 11]}]
Explanation : None duplicate.
方法#1:使用循环
这是可以执行此任务的方式之一。在此,我们对每个字典进行迭代并记忆它,并防止它添加到结果中。
Python3
# Python3 code to demonstrate working of
# Unique Value Lists Dictionaries
# Using loop
# initializing lists
test_list = [{'Gfg': [2, 3], 'is' : [7, 8], 'best' : [10]},
{'Gfg': [2, 3], 'is' : [7], 'best' : [10]},
{'Gfg': [2, 3], 'is' : [7, 8], 'best' : [10]}]
# printing original list
print("The original list : " + str(test_list))
# Using loop to iterate through elements
# result array to also keep track of already occurred elements
res = []
for sub in test_list:
if sub not in res:
res.append(sub)
# printing result
print("List after duplicates removal : " + str(res))
Python3
# Python3 code to demonstrate working of
# Unique Value Lists Dictionaries
# Using list comprehension
# initializing lists
test_list = [{'Gfg': [2, 3], 'is' : [7, 8], 'best' : [10]},
{'Gfg': [2, 3], 'is' : [7], 'best' : [10]},
{'Gfg': [2, 3], 'is' : [7, 8], 'best' : [10]}]
# printing original list
print("The original list : " + str(test_list))
# list comprehension to encapsulate logic in one liner
res = []
[res.append(val) for val in test_list if val not in res]
# printing result
print("List after duplicates removal : " + str(res))
输出
The original list : [{'Gfg': [2, 3], 'is': [7, 8], 'best': [10]}, {'Gfg': [2, 3], 'is': [7], 'best': [10]}, {'Gfg': [2, 3], 'is': [7, 8], 'best': [10]}]
List after duplicates removal : [{'Gfg': [2, 3], 'is': [7, 8], 'best': [10]}, {'Gfg': [2, 3], 'is': [7], 'best': [10]}]
方法#2:使用列表推导
这是可以执行此任务的另一种方式。在这种情况下,采用了与上面类似的方法,只是封装的不同导致了单行的列表理解。
Python3
# Python3 code to demonstrate working of
# Unique Value Lists Dictionaries
# Using list comprehension
# initializing lists
test_list = [{'Gfg': [2, 3], 'is' : [7, 8], 'best' : [10]},
{'Gfg': [2, 3], 'is' : [7], 'best' : [10]},
{'Gfg': [2, 3], 'is' : [7, 8], 'best' : [10]}]
# printing original list
print("The original list : " + str(test_list))
# list comprehension to encapsulate logic in one liner
res = []
[res.append(val) for val in test_list if val not in res]
# printing result
print("List after duplicates removal : " + str(res))
输出
The original list : [{'Gfg': [2, 3], 'is': [7, 8], 'best': [10]}, {'Gfg': [2, 3], 'is': [7], 'best': [10]}, {'Gfg': [2, 3], 'is': [7, 8], 'best': [10]}]
List after duplicates removal : [{'Gfg': [2, 3], 'is': [7, 8], 'best': [10]}, {'Gfg': [2, 3], 'is': [7], 'best': [10]}]