Home > Back-end >  How do you append two dictionaries such that the result of the value is a list of lists
How do you append two dictionaries such that the result of the value is a list of lists

Time:06-24

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.

CodePudding user response:

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

CodePudding user response:

The code snippet below will ensure that even if you don't have a key present on both dictionaries, its value will still be preserved and you won't have an exception:

def merge_two_dicts(dict_a, dict_b):
    merged = dict()
    for key, value in dict_a.items():
        if key in dict_b:
            merged[key] = [value,dict_b[key]]
            dict_b.pop(key, None)
        else:
            merged[key] = [value]
    for key, value in dict_b.items():
            merged[key] = [value]
    return merged

CodePudding user response:

If the two dicts have the same keys but are not in the same order

try to use this:

dd = {1: [10, 15], 3: [7], 5: [10, 20, 27]}
d1 = {1: [1, 4], 5: [2, 5, 6], 3: [3]}
ddd = {}
for k in sorted(dd):
    ddd[k] = [dd[k], d1[k]]

CodePudding user response:

Using an approach more similar to the one use by the OP. It works for any dictionaries, no restrictions on keys a required.

Used defaultdict, a "higher" performant subclass of dict.

from collections import defaultdict

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

dd = defaultdict(list)

for d in d1, d2:
    for k, v in d.items():
        dd[k].append(v)
  • Related