How to quickly merge two dictionaries in Python3

Dictionary merging is often used in data operations. How to merge two or more dictionaries?

Remember when you are in trouble, iteration can solve any problem, haha.

In addition to iteration, there are also some tricks, such as converting to a list first.

In [1]: d1 = {'id': 1, 'name': 'Geek'}                                                                             

In [2]: d2 = {'phone': '13800001111', 'mail': '[email protected]'}                                                       

In [3]: dict(list(d1.items()) + list(d2.items()))                                                                  
Out[3]: {'id': 1, 'name': 'Geek', 'phone': '13800001111', 'mail': '[email protected]'}

Python3.5 After that, there is another syntactic sugar that can be used, which is very convenient!

In [4]: {**d1, **d2}                                                                                               
Out[4]: {'id': 1, 'name': 'Geek', 'phone': '13800001111', 'mail': '[email protected]'}

Guess you like

Origin blog.csdn.net/yilovexing/article/details/107817799