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

How do you append two dictionaries such that the result of the value is a list of lists

I have two dictionaries:

dd = {1: [10, 15], 5: [10, 20, 27], 3: [7]}
dd1 = {1: [1, 4], 5: [2, 5, 6], 3: [3]}

I would like to have the appended dictionary dd look like this:

dd = {1: [[10, 15],[1, 4]], 5: [[10, 20, 27],[2, 5, 6]], 3: [[7],[3]]}

The code I have used to get some what close to this is:

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 dictionary in (dd, dd1):
    for key, value in dictionary.items():
        dd[key].append([value])

This doesn’t quite work as it appends the list into the list opposed to keeping the two lists separate as a list of lists.

>Solution :

Assuming d and d1 have the same keys:

d = {1: [10, 15], 5: [10, 20, 27], 3: [7]}
d1 = {1: [1, 4], 5: [2, 5, 6], 3: [3]}

dd = d

for k, v in d1.items():
    dd[k] = [dd[k], v]

print(dd)

Output:

{1: [[10, 15], [1, 4]], 5: [[10, 20, 27], [2, 5, 6]], 3: [[7], [3]]}

Alternative method:

d = {1: [10, 15], 5: [10, 20, 27], 3: [7]}
d1 = {1: [1, 4], 5: [2, 5, 6], 3: [3]}

dd = {}

for key in d.keys():
    dd[key] = [d[key], d1[key]]

print(dd)

Output:

{1: [[10, 15], [1, 4]], 5: [[10, 20, 27], [2, 5, 6]], 3: [[7], [3]]}
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