Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

merging Python dictionaries

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?

like image 286
Joey Avatar asked Mar 02 '10 19:03

Joey


People also ask

Can we merge two dictionaries in Python?

Using | in Python 3.9 In the latest update of python now we can use “|” operator to merge two dictionaries. It is a very convenient method to merge dictionaries.

Which function helps merge dictionary?

Merge two dictionaries using Copy() and Update() Method In this method, we copy all the elements of the first dictionary (d1) elements using the copy() function and then assign the copied data into the other dictionary (d3). After that, we update the dictionary d3 with the d2 dictionary using the update() function.

Which function helps merge dictionary d1 and d2?

To merge two dictionaries d1 and d2, create deepcopy(d1) as d and then do the update method. In this way, the original dictionary will not be modified.


2 Answers

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}) 
like image 129
Alex Martelli Avatar answered Oct 08 '22 21:10

Alex Martelli


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]} 
like image 42
Nadia Alramli Avatar answered Oct 08 '22 22:10

Nadia Alramli