1

I am looking to combine two dictionaries by grouping elements that share common keys, but I would also like to account for keys that are not shared between the two dictionaries. For instance given the following two dictionaries.

d1 = {'a':1, 'b':2, 'c': 3, 'e':5}
d2 = {'a':11, 'b':22, 'c': 33, 'd':44}

The intended code would output

df = {'a':[1,11] ,'b':[2,22] ,'c':[3,33] ,'d':[0,44] ,'e':[5,0]}

Or some array like:

df = [[a,1,11] , [b,2,22] , [c,3,33] , [d,0,44] , [e,5,0]]

The fact that I used 0 specifically to denote an entry not existing is not important per se. Just any character to denote the missing value.

I have tried using the following code

df = defaultdict(list)
for d in (d1, d2): 
    for key, value in d.items():
        df[key].append(value)

But get the following result:

df = {'a':[1,11] ,'b':[2,22] ,'c':[3,33] ,'d':[44] ,'e':[5]}

Which does not tell me which dict was missing the entry.

I could go back and look through both of them, but was looking for a more elegant solution

  • I get no lookup errors with your code. It works perfectly fine. – Unmitigated Feb 14 '23 at 00:21
  • Check out `setdefault()` – JonSG Feb 14 '23 at 00:24
  • Several of the techniques from the linked duplicate will address the problem - just modify it so that, when the code checks for a key in the "source" dictionaries, it `.get`s a default for missing keys. Either that, or pre-process the dicts to fill in the missing keys first. – Karl Knechtel Feb 14 '23 at 01:55

2 Answers2

3

You can use a dict comprehension like so:

d1 = {'a':1, 'b':2, 'c': 3, 'e':5}
d2 = {'a':11, 'b':22, 'c': 33, 'd':44}
res = {k: [d1.get(k, 0), d2.get(k, 0)] for k in set(d1).union(d2)}
print(res)
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
2

Another solution:

d1 = {"a": 1, "b": 2, "c": 3, "e": 5}
d2 = {"a": 11, "b": 22, "c": 33, "d": 44}

df = [[k, d1.get(k, 0), d2.get(k, 0)] for k in sorted(d1.keys() | d2.keys())]
print(df)

Prints:

[['a', 1, 11], ['b', 2, 22], ['c', 3, 33], ['d', 0, 44], ['e', 5, 0]]

If you do not want sorted results, leave the sorted() out.

Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91