I tried doing a bit of search in SO to find a solution, but I'm still stumped. I think I'm fundamentally misunderstanding something about loops, lists and dictionaries.
I'm largely self-taught and by no means an expert, so apologies in advance if this is an incredibly stupid question.
I have various lists of dictionaries like the l1 and l2 samples in the snippet below. My desired output is something like
l3 = [{'A':1, 'B':4},{'A':2,'B':5},{'A':3,'B':6}
However, no matter what I try I always seem to be getting only the last key-value pair from the second dictionary, i.e.
[{'A': 1, 'B': 6}, {'A': 2, 'B': 6}, {'A': 3, 'B': 6}]
This is what I've got (comments to explain what I'm thinking the code is/should be doing)
# First list of dictionaries
l1 = [{'A': 1},{'A': 2},{'A': 3}]
print(l1)
# Second list of dictionaries
l2 = [{'B': 4},{'B': 5},{'B': 6}]
print(l2)
# Empty list - to receive dictionaries in l1 and l2
l3 =[]
print(l3)
# Adding dictionaries from l1 into l3
for dict1 in l1:
l3.append(dict1)
print(l3)
# Opening l3 to loop through each dictionary, using range(len()) to loop through the index positions
for i in range(len(l3)):
# Opening l2 to loop through each dictionary
for dict2 in l2:
l3[i].update(dict2)
print(l3)
# Tried inverting the lists here, looping through l2 and then looping through l3 to append all dictionaries in l2
for dict2 in l2:
for i in range(len(l3)):
l3[i].update(dict2)
print(l3)
I also tried using zip() and ended up with a list of tuples of dictionaries which makes me think I'm either using that incorrectly, or it's too complex a tool for what I need here. From what I could understand doing some research, the problem is that I keep overriding the values I have just written, I assume that's why I consistently end up with only the last value added everywhere.
Any help appreciated!
The simplest way to merge two dictionaries in python is by using the unpack operator(**). By applying the "**" operator to the dictionary, it expands its content being the collection of key-value pairs.
Python 3.9 has introduced the merge operator (|) in the dict class. Using the merge operator, we can combine dictionaries in a single line of code. We can also merge the dictionaries in-place by using the update operator (|=).
In Python 3.9 and later versions, the | operator can be used to merge dictionaries. Note: If there are two keys with the same name, the merged dictionary contains the value of the latter key.
Your code here is incorrect. For each dict in l3, you update every single dict in l2.
for i in range(len(l3)):
# Opening l2 to loop through each dictionary
for dict2 in l2:
l3[i].update(dict2)
Try this:
for i in range(len(l3)):
l3[i].update(l2[i])
Here is a better solution: The second list dictionary value will overwrite the first one, if they have the same key.
result = list(map(lambda x,y:{**x, **y}, l1, l2))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With