python删除重复元素,Python在组合字典的列表中删除重复值

I need a little bit of homework help. I have to write a function that combines several dictionaries into new dictionary. If a key appears more than once; the values corresponding to that key in the new dictionary should be a unique list. As an example this is what I have so far:

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)

The output looks like:

{'a': ['apple', 'adam'], 'c': ['cat', 'car'], 'b': ['bat', 'bat', 'boy'], 'e': ['elephant'], 'd': ['dog', 'deer']}

Under the 'b' key, 'bat' appears twice. How do I remove the duplicates?

I've looked under filter, lambda but I couldn't figure out how to use with (maybe b/c it's a list in a dictionary?)

Any help would be appreciated. And thank you in advance for all your help!

解决方案

Just test for the element inside the list before adding it: -

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]]

And since you want just unique elements in the value list, then you can just use a Set as value instead. Also, you can use a defaultdict here, so that you don't have to test for key existence before adding.

Also, don't use built-in for your as your variable names. Instead of dict some other variable.

So, you can modify your merge method as:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值