Merge two lists of dictionaries ignoring None entries

Question:

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}]
Asked By: Javi Torre

||

Answers:

You can use a list comprehension with zip.

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

You can use the zip function and a list comprehension to merge the two lists and ignore the None elements. Here is an example of how you can do it:

a = [{'a1': 1, 'a2': 2}, {'a3': 3}, None, {'a4': 4}]
b = [{'b1': 1, 'b2': 2}, None, {'b3': 4, 'b4': 5}, {'b5': 4, 'b6': 5}]

desired_output = [{**d1, **d2} for d1, d2 in zip(a, b) if None not in [d1,d2]]

print(desired_output)

# [{'a1': 1, 'a2': 2, 'b1': 1, 'b2': 2}, {'a4': 4, 'b5': 4, 'b6': 5}]

In this example, the zip function combines the elements of the two lists a and b into pairs (d1, d2). The list comprehension iterates over these pairs, and for each pair, it uses the ** operator to merge the two dictionaries and only considering the case when neither of d1 nor d2 is None.

Answered By: Lahcen YAMOUN
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.