I am trying to merge the following python dictionaries as follow:

dict1= {'paul':100, 'john':80, 'ted':34, 'herve':10}
dict2 = {'paul':'a', 'john':'b', 'ted':'c', 'peter':'d'}

output = {'paul':[100,'a'],
          'john':[80, 'b'],
          'ted':[34,'c'],
          'peter':[None, 'd'],
          'herve':[10, None]}

Is there an efficient way to do this?


Solution 1:

output = {k: [dict1[k], dict2.get(k)] for k in dict1}
output.update({k: [None, dict2[k]] for k in dict2 if k not in dict1})

Solution 2:

This will work:

{k: [dict1.get(k), dict2.get(k)] for k in set(dict1.keys() + dict2.keys())}

Output:

{'john': [80, 'b'], 'paul': [100, 'a'], 'peter': [None, 'd'], 'ted': [34, 'c'], 'herve': [10, None]}