Let’s say I have three different dictionaries:
dictA = {'A': 1, 'B': 2, 'C': 3}
dictB = {'C': 1, 'D': 2, 'E': 3}
dictC = {'A': 2, 'C': 4, 'E': 6, 'G': 8}
And I want to “add” these dictionaries together, in the dictA+dictB+dictC
order. What I mean by that is:
-
values with the same keys will be added together (for example
'A': 1
in dictA and'A': 2
in dictB will become'A': 3
in the end) -
values without a previously existing key will be created (for example during
dictB + dictC
, the key'G'
does not exist, so it will be created)
The result for this example should look something like this:
resultDict = {'A': 3, 'B': 2, 'C': 8, 'D': 2, 'E': 9, 'G': 2,}
Is there an easy way to do this? The dictionaries I am actually working with are much larger and nested in multiple other dictionaries, so sorry if this example isn’t well explaining. I tried fidgeting around with for loops but as I mentioned, the lists I am actually working with are much larger and not that easy to work with.
mrelpa is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.