合并两个字典并在python中删除重复项 [英] Combine two dictionaries and remove duplicates in python

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

问题描述

我有两个不同的字典.我正在尝试通过删除重复项来合并这两个.这是两个列表.

Hi I have two different dictionaries. And I am trying to merge those two by removing the duplicates. These are the 2 lists.

x = [{'relevance': 0.722, 'type': 'Company', 'name': 'Dell'}, {'relevance': 0.314, 'type': 'OperatingSystem', 'name': 'VMs'}, {'relevance': 0.122, 'type': 'Technology', 'name': 'iSCSI'}, {'relevance': 0.266, 'type': 'Company', 'name': 'Force10'}, {'relevance': 0.327, 'type': 'Person', 'name': 'Greg Althaus'}, {'relevance': 0.085, 'type': 'URL', 'name': 'http://Dell.com/OpenStack'}, {'relevance': 0.174, 'type': 'Company', 'name': 'Storage Hardware'}]
y = [{'relevance': u'0.874065', 'type': u'Company', 'name': u'Dell'}, {'relevance': u'0.522169', 'type': u'OperatingSystem', 'name': u'VMs'}, {'relevance': u'0.444586', 'type': u'Person', 'name': u'Rob Hirschfeld'}, {'relevance': u'0.413988', 'type': u'Person', 'name': u'Greg Althaus'}, {'relevance': u'0.376489', 'type': u'FieldTerminology', 'name': u'iSCSI'}, {'relevance': u'0.314059', 'type': u'Company', 'name': u'Force10'}]

我尝试做

z = x.update(y)
print x

它给了我这个错误

AttributeError: 'str' object has no attribute 'update'`

我已经尝试过了

z = dict(x.items() + y.items())

它给了我这个错误

AttributeError: 'str' object has no attribute 'items'

然后我尝试了

z = dict(x, **y)

它给了我这个错误

TypeError: type object argument after ** must be a mapping, not str

然后我尝试了

z = dict(chain(x.iteritems(), y.iteritems()))

它给了我这个错误

AttributeError: 'str' object has no attribute 'iteritems'

推荐答案

如果您希望创建新的词典列表并希望通过删除重复项来合并它们,那么这将很简单.

If you wish to create a new list of dictionaries and wish to merge them by removing duplicates, this would simple work.

def DictListUpdate( lis1, lis2):
    for aLis1 in lis1:
        if aLis1 not in lis2:
            lis2.append(aLis1)
    return lis2

x = [ {"name": "surya", "company":"dell"}, \
       {"name": "jobs", "company":"apple"} ]

y = [ { "name": "surya", "company":"dell"}, \
    { "name": "gates", "company": "microsoft"} ]

print DictListUpdate(x,y)

输出:

>>> 
[{'company': 'dell', 'name': 'surya'}, {'company': 'microsoft', 'name': 'gates'}, {'company': 'apple', 'name': 'jobs'}]

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

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