Home > Back-end >  missing values in dictionary what merged
missing values in dictionary what merged

Time:08-10

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

CodePudding user response:

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()}

CodePudding user response:

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

CodePudding user response:

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}

CodePudding user response:

You can union keys of two dict by using set(dict_1) | set(dict_2) (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.

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

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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

  • Related