双重字典删除信息 python_合并两个字典并在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'}]

I have tried doing

z = x.update(y)

print x

It gave me this error

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

I have tried this

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

It gave me this error

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

Then I tried

z = dict(x, **y)

It gave me this error

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

Then I tried

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

It gave me this error

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)

Output:

>>>

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值