Home > OS >  How to merge multi array of object in python?
How to merge multi array of object in python?

Time:10-13

I have two list of array, I don't know How I can merge multi array of object in python?

[{'name': 'James'}, {'name': 'Abhinay'}, {'name': 'Peter'}]

[{'age': 1}, {'age': 2}, {'age': 3}]

what I want

[{'name': 'James','age':1}, {'name': 'Abhinay','age':2}, {'name': 'Peter','age':3}]

CodePudding user response:

Here's one approach that can work:

L1 = [{'name': 'James'}, {'name': 'Abhinay'}, {'name': 'Peter'}]
L2 = [{'age': 1}, {'age': 2}, {'age': 3}]

result = [dict(**x, **y) for x, y in zip(L1, L2)]

print(result)
# [{'name': 'James', 'age': 1}, {'name': 'Abhinay', 'age': 2}, {'name': 'Peter', 'age': 3}]

Using the dict union | operator in Python 3.9 or higher:

result = [x | y for x, y in zip(L1, L2)]
  • Related