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
Advertisement
Answer
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)
