Append lists of a dictionary

Question:

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']}
Asked By: Joe

||

Answers:

You can just iterate one of the two dictionaries and extend the list:

for k in n:
     n[k].extend(m[k])

print(n)

{'d1': [1, 2, 3, 4, 5], 'd2': ['a', 'b', 'c', 'd', 'e']}
Answered By: JNevill
  • You can’t use k twice, 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']}
Answered By: DeepSpace

I have commented the changes and explanation in the code. You can also use the extend function instead of the inner loop but time complexity remains the same in both cases.

n = {'d1': [1, 2, 3], 'd2': ['a', 'b', 'c']}
m = {'d1': [4, 5], 'd2': ['d', 'e']}

for i in n:             #iterates through the keys in n
    for j in m[i]:      #to iterate through the same key in m
        n[i].append(j)  
print(n)

output:

{'d1': [1, 2, 3, 4, 5], 'd2': ['a', 'b', 'c', 'd', 'e']}
Answered By: AMISH GUPTA

You can iterate key/value pairs and extend from that information

n = {'d1': [1, 2, 3], 'd2': ['a', 'b', 'c']}
m = {'d1': [4, 5], 'd2': ['d', 'e']}
for key, vlist in n.items():
    vlist.extend(m.get(key, []))

This avoids a lookup in n which should be a little faster.

Answered By: tdelaney
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.