Python在组合字典的列表中删除重复值 [英] Python remove duplicate value in a combined dictionary's list

查看:563
本文介绍了Python在组合字典的列表中删除重复值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一点家庭作业的帮助。我必须编写一个将几个词典组合成新词典的函数。如果钥匙出现不止一次;新词典中与该键对应的值应该是唯一的列表。作为一个例子,这是我迄今为止所做的:

  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 d中的dict:
在dict.items()中的k:
如果k [0]在newdicts中:
newdicts [k [0]]。append(k [1])$ ​​b $ b else:
newdicts [k [0]] = [k [1]]
return newdicts

组合=合并(f,g,h,r)
打印(合并)

输出如下:



{'a':['apple','adam'],'c':['cat','car'],'b ''['蝙蝠','蝙蝠','男孩'],'e':['elephant'],'d':['dog','deer']}



在b键下,bat出现两次。我如何删除重复的文件?



我已经看过滤镜,lambda,但我无法弄清楚如何使用(也许b / c它是一个列表一个字典?)



任何帮助将不胜感激。谢谢你所有的帮助!

解决方案

在添加列表之前,测试列表中的元素:如果k(0)在newdicts中,则

  1]不在newdicts [k [0]]:#在添加前做这个测试。 
newdicts [k [0]]。append(k [1])$ ​​b $ b else:
newdicts [k [0]] = [k [1]]






由于您只想在列表,那么您可以使用 Set 作为值。此外,您可以在此处使用 defaultdict ,以便在添加之前不必对密钥存在进行测试。



此外,不要使用内置的作为您的变量名。而不是 dict 其他一些变量。



所以,你可以修改你的 code>方法为:

 从集合导入defaultdict 

def merge(* d) :
newdicts = defaultdict(set)#在d中为each_dict定义一个defaultdict


#dict.items()返回一个(k,v)元组的列表。
#所以,你可以在两个循环变量中直接解包元组。
for k,v in each_dict.items():
newdicts [k] .add(v)

#如果你想要确切的表示,你已经显示
#你可以用新建的dict命令创建一个正常的命令。
unique = {key:list(value)为key,value in newdicts.items()}
返回唯一


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

这篇关于Python在组合字典的列表中删除重复值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆