Mizzle Lee
Mizzle Lee

Reputation: 31

How to merge list of dicts

How to merge a list of dictionaries in Python? I have 2 sets of data:

a = [{'date':'1/1/2019'},{'date':'1/1/2020'},{'date':'1/1/2021'}]
b = [{'value':'2'},{'value':'5'},{'value':'6'}]

How can I merge it to the below result?

[{'date':'1/1/2019','value':'2'},
 {'date':'1/1/2020','value':'5'},
 {'date':'1/1/2021','value':'6'}]

Upvotes: 3

Views: 540

Answers (5)

Pavel
Pavel

Reputation: 107

Assuming that both are lists of dicts of the same length, you can do:

c = [{**item[0], **item[1]} for item in zip(a, b)]

Upvotes: 4

Cdaman
Cdaman

Reputation: 320

there are two methods for doing that. One is :

for i in range(len(a)):
    a[i].update(b[i])
    
print(a)

if you have python 3.9 and above

new_list = [a[i]|b[i] for i in range(len(a))]

for checking your python version:

import sys
print (sys.version)

Upvotes: 0

Prakash Dahal
Prakash Dahal

Reputation: 4875

c = [{**a1, **b1} for a1,b1 in zip(a,b)]

Here I have used list comprehension, **a1 and **b1 are used for unpacking and mapping the key-value pair of both list of dictionaries

Upvotes: 6

Mark Tolonen
Mark Tolonen

Reputation: 177546

In Python 3.9, The union operator is added to dict, so this works:

>>> a = [{'date':'1/1/2019'},{'date':'1/1/2020'},{'date':'1/1/2021'}]
>>> b = [{'value':'2'},{'value':'5'},{'value':'6'}]
>>> [x|y for x,y in zip(a,b)]
[{'date': '1/1/2019', 'value': '2'}, {'date': '1/1/2020', 'value': '5'}, {'date': '1/1/2021', 'value': '6'}]

See PEP 584 for details.

Upvotes: 7

brunoff
brunoff

Reputation: 4209

[{**i[0],**i[1]} for i in zip(a,b)]

Upvotes: 2

Related Questions