Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Append lists of a dictionary

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 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']}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading