Home > Software engineering >  Merge two lists of dictionaries ignoring None entries
Merge two lists of dictionaries ignoring None entries

Time:01-25

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}]

CodePudding user response:

You can use a list comprehension with zip.

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

CodePudding user response:

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.

  • Related