Reputation: 49
lst1 = [
{'mem': '20.0', 'name': 'p1', 'cpu': '20.0'},
{'mem': '20.0', 'name': 'p2', 'cpu': '20.0'},
{'mem': '20.0', 'name': 'p3', 'cpu': '20.0'},
{'mem': '20.0', 'name': 'p4', 'cpu': '20.0'}
]
lst2 = [
{'pid': 814, 'name': 'p1'},
{'pid': 999, 'name': 'p2'},
{'pid': 1006, 'name': 'p3'},
{'pid': 1152, 'name': 'p4'}
]
I need to merge above two list into single list i.e.
lst3 = [
{'mem': '20.0', 'name': 'p1', 'cpu': '20.0', 'pid':814},
{'mem': '20.0', 'name': 'p2', 'cpu': '20.0','pid':999},
{'pid': 1006, 'mem': '20.0', 'name': 'p3', 'cpu': '20.0'},
{'pid': 1152,'mem': '20.0', 'name': 'p4', 'cpu': '20.0'}
]
I have tried doing it in below way
lst3 = list()
test = dict()
for f,b in zip(lst1,lst2):
test = f.copy()
test.update(b)
#print test
lst3.append(test)
print lst3
Please let me know is there any easy method or more pythonic way to do this
Upvotes: 0
Views: 89
Reputation: 2122
l1 = [{'id': 1, 'name': 'test'}, {'id': 2, 'name': 'test1'}]
l2 = [{'id': 3, 'age': 10},{'id': 4, 'age': 10},{'id': 1, 'age': 10}, {'id': 2, 'age': 20}]
def m1(l1,l2):
d = defaultdict(dict)
for l in (l1,l2):
for d1 in l :
d[d1['id']].update(d1)
aa = sorted(d.values(),key = itemgetter('id'))
aap = print(aa)
return aap
m1(l1,l2)
"""
output :
[{'id': 1, 'name': 'test', 'age': 10}, {'id': 2, 'name': 'test1', 'age': 20}, {'id': 3, 'age': 10}, {'id': 4, 'age': 10}]
"""
Upvotes: 0
Reputation: 51165
Just use zip
and merge, as long as both lists are ordered relative to each other:
out = [{**i, **j} for i, j in zip(lst1, lst2)]
# Result
[{'cpu': '20.0', 'mem': '20.0', 'name': 'p1', 'pid': 814},
{'cpu': '20.0', 'mem': '20.0', 'name': 'p2', 'pid': 999},
{'cpu': '20.0', 'mem': '20.0', 'name': 'p3', 'pid': 1006},
{'cpu': '20.0', 'mem': '20.0', 'name': 'p4', 'pid': 1152}]
Matches output:
In [292]: out == lst3
Out[292]: True
If the lists are not guaranteed to be sorted, you can sort on the common key, in this case name
, before applying my method:
lst1, lst2 = (sorted(i, key=lambda x: x['name']) for i in [lst1, lst2])
Personally, I think your current method works fine, and it is very clear what you are doing. Also, my method of merging exclusively works in Python 3.5+
Upvotes: 2