Python删除组合字典中的重复值';s列表
我需要一点家庭作业的帮助。我必须编写一个函数,将多个词典合并到新词典中。如果某个键出现多次;新字典中对应于该键的值应该是唯一的列表。作为一个例子,这就是我到目前为止所做的:Python删除组合字典中的重复值';s列表,python,list,dictionary,key,duplicates,Python,List,Dictionary,Key,Duplicates,我需要一点家庭作业的帮助。我必须编写一个函数,将多个词典合并到新词典中。如果某个键出现多次;新字典中对应于该键的值应该是唯一的列表。作为一个例子,这就是我到目前为止所做的: f = {'a': 'apple', 'c': 'cat', 'b': 'bat', 'd': 'dog'} g = {'c': 'car', 'b': 'bat', 'e': 'elephant'} h = {'b': 'boy', 'd': 'deer'} r = {'a': 'adam'} def merge(*d
f = {'a': 'apple', 'c': 'cat', 'b': 'bat', 'd': 'dog'}
g = {'c': 'car', 'b': 'bat', 'e': 'elephant'}
h = {'b': 'boy', 'd': 'deer'}
r = {'a': 'adam'}
def merge(*d):
newdicts={}
for dict in d:
for k in dict.items():
if k[0] in newdicts:
newdicts[k[0]].append(k[1])
else:
newdicts[k[0]]=[k[1]]
return newdicts
combined = merge(f, g, h, r)
print(combined)
输出如下所示:
{'a':['apple','adam','c':['cat','car','b':['bat','bat','boy','e':['elephant','d':['dog','deer']}
在“b”键下,“bat”出现两次。如何删除重复项
我已经在filter,lambda下查看过了,但我不知道如何使用(可能是b/c,它是字典中的一个列表?)
任何帮助都将不胜感激。提前感谢你的帮助 添加列表之前,只需测试列表中的元素:-
for k in dict.items():
if k[0] in newdicts:
if k[1] not in newdicts[k[0]]: # Do this test before adding.
newdicts[k[0]].append(k[1])
else:
newdicts[k[0]]=[k[1]]
由于在
值
列表中只需要唯一的元素,因此可以使用集
作为值。此外,您可以在此处使用defaultdict
,这样您就不必在添加之前测试密钥是否存在
另外,不要使用内置的作为变量名。而不是dict
其他变量
因此,您可以将merge
方法修改为:
from collections import defaultdict
def merge(*d):
newdicts = defaultdict(set) # Define a defaultdict
for each_dict in d:
# dict.items() returns a list of (k, v) tuple.
# So, you can directly unpack the tuple in two loop variables.
for k, v in each_dict.items():
newdicts[k].add(v)
# And if you want the exact representation that you have shown
# You can build a normal dict out of your newly built dict.
unique = {key: list(value) for key, value in newdicts.items()}
return unique
在for循环中添加以下内容:
for dict in d:
for k in dict.items():
if k[0] in newdicts:
# This line below
if k[1] not in newdicts[k[0]]:
newdicts[k[0]].append(k[1])
else:
newdicts[k[0]]=[k[1]]
这样可以确保不添加重复项
>>> import collections
>>> import itertools
>>> uniques = collections.defaultdict(set)
>>> for k, v in itertools.chain(f.items(), g.items(), h.items(), r.items()):
... uniques[k].add(v)
...
>>> uniques
defaultdict(<type 'set'>, {'a': set(['apple', 'adam']), 'c': set(['car', 'cat']), 'b': set(['boy', 'bat']), 'e': set(['elephant']), 'd': set(['deer', 'dog'])})
{'a':['apple'、'adam']、'c':['car'、'cat']、'b':['boy'、'bat']、'e':['elephant']、'd':['deer'、'dog']}当您想要独特的元素时,请使用集合:
def merge_dicts(*d):
result={}
for dict in d:
for key, value in dict.items():
result.setdefault(key, set()).add(value)
return result
尽量避免使用索引;而是解包元组。感谢您提供了一个非常好/简单的解决方案,以及您的解释/评论。真的很感激,因为我正在学习。
def merge_dicts(*d):
result={}
for dict in d:
for key, value in dict.items():
result.setdefault(key, set()).add(value)
return result