Home > Back-end >  Append lists of a dictionary
Append lists of a dictionary

Time:08-20

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']}

CodePudding user response:

  • 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']}

CodePudding user response:

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']}

CodePudding user response:

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']}

CodePudding user response:

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.

  • Related