I have a dictionary with values are lists.
n = {'d1': [1, 2, 3], 'd2': ['a', 'b', 'c']}
m = {'d1': [4, 5], 'd2': ['d', 'e']}
I am trying to have as an output.
{'d1': [1, 2, 3, 4, 5], 'd2': ['a', 'b', 'c', 'd', 'e']}
I tried the following:
for k in n:
for k in m:
n[k] += m[k]
The above code gives a wrong output.
> print(n)
> {'d1': [1, 2, 3, 4, 5, 4, 5], 'd2': ['a', 'b', 'c', 'd', 'e', 'd', 'e']}
>Solution :
- You can’t use
ktwice, the inner one overrides the outer one. - You never check if you are adding the same keys.
Assuming n is the "master" dictionary, you don’t even need the inner loop:
for k in n:
n[k] += m[k]
will result with n being
{'d1': [1, 2, 3, 4, 5], 'd2': ['a', 'b', 'c', 'd', 'e']}