【Python茴香豆系列】之 字典合并#

用 Python 编程,使用不同的方法来完成同一个目标,有时候是一件很有意思的事情。这让我想起鲁迅笔下的孔乙己。孔乙己对于茴香豆的茴字的四种写法颇有研究。我不敢自比孔乙己,这里搜集一些 Python 的茴香豆,以飨各位码农。

假设有字典 x 和字典 y , BOSS 需要把他们合并,生成一个新的字典 z , x 和 y 保持不变。要实现的效果如下:

x = {'a': 1, 'b': 2}
y = {'b': 8, 'c': 9}

经过处理后

z = {'a': 1, 'b': 8, 'c': 9}
[1]:
# 这里先做一些准备工作
x = {'a': 1, 'b': 2}
y = {'b': 8, 'c': 9}

茴香豆一: update#

如果你的 Python 版本小于等于 3.4 ,那么如下方法应该是最常见的:

[2]:
z = x.copy()
z.update(y)
z
[2]:
{'a': 1, 'b': 8, 'c': 9}

茴香豆二: 两个小星星#

如果你已经完全抛弃了 2 ,并且 Python 版本已经大于等于 3.5 ,那么可以这样:

[3]:
z = {**x, **y}
z
[3]:
{'a': 1, 'b': 8, 'c': 9}

茴香豆三: 一条竖杠#

什么?你的 Python 版本已经大于等于 3.9 了?好吧, z = x | y 就能解决问题。

茴香豆四: ChainMap#

ChainMap 可能对大多数开发者来说有点陌生,其特点是:“先入为主”,所以要注意两个字典的顺序。

[4]:
from collections import ChainMap
z = dict(ChainMap(y, x))
z
[4]:
{'a': 1, 'b': 8, 'c': 9}

茴香豆五: Dict#

这个方法仅限于字典的 Key 均为 string 时有效:

[5]:
z = dict(x, **y)
z
[5]:
{'a': 1, 'b': 8, 'c': 9}

茴香豆六: Dict#

这个方法仅限于字典的 Key 均为 string 时有效:

[6]:
# Python 2
# z = dict(x.items() + y.items())
z = dict(x.items() | y.items())
z
[6]:
{'c': 9, 'a': 1, 'b': 2}
{k: v for d in dicts for k, v in d.items()} # iteritems in Python 2.7

or in python 2.6 (and perhaps as early as 2.4 when generator expressions were introduced):

dict((k, v) for d in dicts for k, v in d.items()) # iteritems in Python 2

itertools.chain will chain the iterators over the key-value pairs in the correct order:

from itertools import chain
z = dict(chain(x.items(), y.items())) # iteritems in Python 2

{k: v for x in dicts for k, v in y.items()} # iteritems in Python 2.7