Aaron Fehir
Aaron Fehir

Reputation: 49

How can I update a list of dictionaries with a second list of dictionaries?

So I have been working on this for hours and have scoured many similar questions on Stackoverflow for a response, but no dice. It seems simple enough, but I just can't seem to get the desired result. I have one list of dictionaries, A, that I would like to merge with another list of dictionaries, B. A and B are the same length. I want a resulting list of dictionaries C that is also the same length such that the key:value pairs in B are appended to the existing key:value pairs in A. An example and unsuccessful attempt to achieve the desired result is below.

A = [{'a':1, 'b':2, 'c':3},{'a':4, 'b':5, 'c':6},{'a':7, 'b':8, 'c':9}]
B = [{'d':10},{'d':11},{'d':12}]

for a in A:
    for b in B:
        C = a.update(b)

print(C)

//Actual output: None
//Desired output: [{'a':1, 'b':2, 'c':3, 'd':10},{'a':4, 'b':5, 'c':6, 'd':11},{'a':7, 'b':8, 'c':9, 'd':12}]

In theory, it seems to me like the above code should work, but it does not. Any help would be greatly appreciated.

Thanks, Aaron

Upvotes: 1

Views: 1989

Answers (3)

Asker
Asker

Reputation: 1685

The other answers have focused on providing ways of doing things, but this answer will review why your given code didn't work the way you wanted.

for a in A:
    for b in B:
        C = a.update(b)

print(C)

prints None because the update function always returns None, so that after the statement

C = a.update(b)

you've set the value of C to None! The point of update is to update the given dict in place, without returning anything.

Another issue is that you are looping over all elements of B for each element of A, which is going to have the effect of calling update three times for each element of A. Not what we want!

As @tevemadar says in their excellent answer, the fastest way to achieve what you want is to use the zip function.

Upvotes: 2

hiro protagonist
hiro protagonist

Reputation: 46859

this is an option using zip to iterate over both lists simultaneously and then creating a new dictionary from the original ones:

A = [{'a': 1, 'b': 2, 'c': 3}, {'a': 4, 'b': 5, 'c': 6}, {'a': 7, 'b': 8, 'c': 9}]
B = [{'d': 10}, {'d': 11}, {'d': 12}]

C = [{**a, **b} for a, b in zip(A, B)]
# [{'a': 1, 'b': 2, 'c': 3, 'd': 10}, {'a': 4, 'b': 5, 'c': 6, 'd': 11}, {'a': 7, 'b': 8, 'c': 9, 'd': 12}]

with python 3.9 you should be able to do this with | (see PEP584 or the doc):

C = [a | b for a, b in zip(A, B)]

Upvotes: 3

tevemadar
tevemadar

Reputation: 13195

Meet zip, it iterates through multiple lists in parallel:

A = [{'a':1, 'b':2, 'c':3},{'a':4, 'b':5, 'c':6},{'a':7, 'b':8, 'c':9}]
B = [{'d':10},{'d':11},{'d':12}]
for a,b in zip(A,B):
  a.update(b)
print(A)

Upvotes: 2

Related Questions