0

I am trying to join dictionaries in this way:

d1 = {1: [1, 2, 3], 2: [5, 4, 35]}
d2 = {1: [4, 5, 6], 2: [32, 54, 102]}
d3 = {3: [943, 23, 111, 3], 1: [7, 8, 9]}

dictionary_result = {1: [1, 2, 3, 4, 5, 6, 7, 8, 9], 2: [5, 4, 35, 32, 54, 102], 3: [943, 23, 111,3]}

I tried this, but only works for 2 dictionaries

from collections import defaultdict
a, b = {1: [2, 3], 2: [3]}, {1: [4], 3: [1]}
de = defaultdict(list, a)
for i, j in b.items():
    de[i].extend(j)

So, how can I join N dictionaries like this efficiently?

Chariot
  • 55
  • 1
  • 13
  • Look why defaultdict is better than setdefault https://stackoverflow.com/questions/38625608/setdefault-vs-defaultdict-performance and maybe change the accepted answer ;) – azro Mar 27 '21 at 11:46

2 Answers2

3

you can use dictionary method setdefault.
This is how setdefault works: If the key is in the dictionary it returns its value otherwise insert a key with a value of default(which is a list in this case) and return default.

dictionary_result = {}
for d in d1, d2, d3:
    for key, value in d.items():
        dictionary_result.setdefault(key, []).extend(value)

Output:

{1: [1, 2, 3, 4, 5, 6, 7, 8, 9], 2: [5, 4, 35, 32, 54, 102], 3: [943, 23, 111, 3]}
Vishal Singh
  • 6,014
  • 2
  • 17
  • 33
2

Add an outer loop, that runs over the different dicts to use as update:

result = defaultdict(list)
for d in d1, d2, d3:
    for i, j in d.items():
        result[i].extend(j)
azro
  • 53,056
  • 7
  • 34
  • 70
  • No reason to treat `d1` differently; just start with an empty `defaultdict(list)`. The way this currently works, you're mutating the lists in `d1`, which is probably undesirable. – kaya3 Mar 24 '21 at 19:36
  • @kaya3 It avoid looping over it, so better performance – azro Mar 24 '21 at 19:36
  • How exactly do you think `defaultdict(list, d1)` avoids looping over `d1`? – kaya3 Mar 24 '21 at 19:37
  • @kaya3 don't really know how is the implem, I'd guess it doesn't iterate over the dict, but use it directly or smth – azro Mar 24 '21 at 19:38