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