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:

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

Leave a Reply