Merge two lists of dictionaries ignoring None entries

Advertisements

I have the below two lists:

a = [{'a1': 1, 'a2': 2}, {'a3': 3}]
b = [{'b1': 1, 'b2': 2}, None]

I would like to merge them creating an output like the below, ignoring the None elements.

desired_output = [{'a1': 1, 'a2': 2, 'b1': 1, 'b2': 2}, {'a3': 3}]

>Solution :

You can use a list comprehension with zip.

res = [(x or {}) | (y or {}) for x, y in zip(a, b)]

Leave a Reply Cancel reply