Python: Merge 2 dictionaries and add 0 if key is empty

Viewed 104

I have 2 dicts as follows:

d1 = {a:2, b:4}
d2 = {a:13, b:3, c:5}

How to merge these two and add 0 if one key is empty?

The result should be

= {a:[2,13], b:[4,3], c:[0,5]}
  

I tried to use this

d1 = {'a':2, 'b':4}
    d2 = {'a':13, 'b':3, 'c':5}

    dd = defaultdict(list)

    
    for d in (d1, d2): 
        for key, value in d.items():
            dd[key].append(value)

but I don't know how to add 0, I'm really new to programming.

2 Answers

You can get the list of keys then generate the required dictionary by using dict.get and default value as 0

d1 = {'a':2, 'b':4}
d2 = {'a':13, 'b':3, 'c':5}

keys = set((*d1.keys(), *d2.keys()))

new_dict = {k: [d.get(k, 0) for d in [d1, d2]] for k in keys}

print(new_dict) #{'a': [2, 13], 'b': [4, 3], 'c': [0, 5]}

Use below code.

d1 = {'a':2, 'b':4}
d2 = {'a':13, 'b':3, 'c':5}

keys = set((*d1.keys(), *d2.keys()))
result={}

for k in keys:
    result[k]=list((d1.get(k, 0), d2.get(k,0)))
print(result)#{'a': [2, 13], 'b': [4, 3], 'c': [0, 5]}
Related