missing values in dictionary what merged

Question:

I have 2 dictionary a = {1:6, 2:7, 3:8} and b = {1:5, 3:9}
I want to merge them in this shape
c = {1:[6, 5], 2:[7, null], 3:[8, 9]}
And another thing is I have more than 2 dictionaries they are lots of dictionaries

Asked By: Novinnam

||

Answers:

Try:

a = {1: 6, 2: 7, 3: 8}
b = {1: 5, 3: 9}

out = {}
for k in a.keys() | b.keys():
    out[k] = [a.get(k), b.get(k)]

print(out)

Prints:

{1: [6, 5], 2: [7, None], 3: [8, 9]}

Or one-liner:

out = {k: [a.get(k), b.get(k)] for k in a.keys() | b.keys()}

For more dicts:

a = {1: 6, 2: 7, 3: 8}
b = {1: 5, 3: 9}
c = {2: 1, 3: 10}

all_dicts = [a, b, c]

out = {}
for k in {k for d in all_dicts for k in d}:
    out[k] = [d.get(k) for d in all_dicts]

print(out)

Prints:

{1: [6, 5, None], 2: [7, None, 1], 3: [8, 9, 10]}
Answered By: Andrej Kesely

You can use set.union to get the union keys of two dictionary

d = {k: [a.get(k), b.get(k)]  for k in set(a).union(set(b))}
print(d)

{1: [6, 5], 2: [7, None], 3: [8, 9]}
Answered By: Ynjxsjmh

You can pass your longest dictionary in a kind of left join operation:

new = {x:[a.get(x,None),b.get(x,None)] for x in a}
Answered By: Celius Stingher

Update base the comment for multiple dicts

You can union keys of multiple dicts by using set().union(*dcts) (because dict return keys). At the end we can use dict.get() and the default value of this function is None if the key doesn’t exist.

a = {1:6, 2:7, 3:8}
b = {1:5, 3:9}
c = {1:7, 3:10, 4:11}

dcts = [a, b, c]

res = {k: [dct.get(k) for dct in dcts] for k in set().union(*dcts)}
print(res)

{1: [6, 5, 7], 2: [7, None, None], 3: [8, 9, 10], 4: [None, None, 11]}
Answered By: I'mahdi

You can make a function using a loop through the distinct keys:

def combine(*dicts):
    return {k: [d.get(k) for d in dicts] for k in set().union(*dicts)}

>>> combine(a, b)
{1: [6, 5], 2: [7, None], 3: [8, 9]}
Answered By: Jab
a = {1:6, 2:7, 5:8}
b = {1:5, 3:9}
c = {}

max_key = max(max(list(a.keys())), max(list(b.keys())))

for i in range(max_key):
    c[i+1] = [a.get(i+1), b.get(i+1)]

print(c)

Result:

{1: [6, 5], 2: [7, None], 3: [None, 9], 4: [None, None], 5: [8, None]}
Answered By: Burkhon Nurmurodov

As the question originally had a tag:

import pandas as pd

out = (pd.concat([pd.Series(a), pd.Series(b)], axis=1) # as many series as you want
         .convert_dtypes().replace({pd.NA: None}) # optional
         .T.to_dict('list')
       )

output: {1: [6, 5], 2: [7, None], 3: [8, 9]}

any number of dictionaries

import pandas as pd

dicts = [a, b, c, d] # add all the dictionaries in the list

out = (pd.concat([pd.Series(d) for d in dicts], axis=1)
         .convert_dtypes().replace({pd.NA: None}) # optional
         .T.to_dict('list')
       )
Answered By: mozway
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.