Python3 如何快速和并两个字典

字典合并在数据操作中经常用到,如何合并两个或多个字典呢?

遇事不决就记住,迭代可以解决任何问题,哈哈。

除了迭代也有些小技巧,比如先转为列表。

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 之后还有个语法糖可以用,很方便!

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

猜你喜欢

转载自blog.csdn.net/yilovexing/article/details/107817799