python合并2个字典

2种方式,update()和items()方式

In [14]: a
Out[14]: {'a': 1, 'b': 2, 'c': 3}

In [15]: c = {'d': 4}

In [16]: a.update(c)

In [17]: a
Out[17]: {'a': 1, 'b': 2, 'c': 3, 'd': 4}

In [18]: a = {'a': 1}

In [19]: a
Out[19]: {'a': 1}

In [20]: c
Out[20]: {'d': 4}

In [21]: a.items() + c.items()
Out[21]: [('a', 1), ('d', 4)]

In [22]: dict(a.items() + c.items())
Out[22]: {'a': 1, 'd': 4}

In [29]: z = a.update(b)

In [30]: z

 

直接赋值给新的变量是不可以的,这样z得到的是空值,这里需要去看一下update的用法了,

见http://www.tutorialspoint.com/python/dictionary_update.htm

此函数不返回任何值,orz,所以没有任何值

同时可以用来更新字典里的值

In [35]: a.update({'a': 2})

In [36]: a
Out[36]: {'a': 2, 'c': 3}

In [37]: a.update({'a': 3, 'd': 'd'})

In [38]: a
Out[38]: {'a': 3, 'c': 3, 'd': 'd'}

  

原文地址:https://www.cnblogs.com/wswang/p/5489629.html