Python3 - 如何合并词典

Python3 - 如何合并词典

本文讲一下几种合并 python 字典的方法。并做一些简要分析。 假设是有两个字典 x,y

1
2
3
x = {'a':1, 'hello': 'world'}
y = {'b':2, 'hello': 'kitty'}

  • 方法一
1
2
3
4
5
6
z = {**x, **y}
print(z)

z = {**x, 'foo': 1, 'bar': 2, **y}
print(z)

输出

1
2
{'a': 1, 'hello': 'kitty', 'b': 2}
{'a': 1, 'hello': 'kitty', 'foo': 1, 'bar': 2, 'b': 2}
  • 方法二
1
2
3
4
5
6
def merge_two_dicts(x, y):
    z = x.copy()   # start with x's keys and values
    z.update(y)    # modifies z with y's keys and values & returns None
    return z
z = merge_two_dicts(x, y)
print(z)

输出

1
{'a': 1, 'hello': 'kitty', 'b': 2}
  • 方法三
1
2
z = dict(x, **y)
print(z)

输出

1
{'a': 1, 'hello': 'kitty', 'b': 2}

这个方法有一点 trick,做一下解释,其实第二个参数**y是通过 dict 的构造函数’keyword arguments’传递给词典,表面上并无合并语义。但整体实现了合并功能,而且性能指标相对不错。

  • 方法四
1
2
z= {k: v for d in [x,y] for k, v in d.items()}
print(z)

输出

1
{'a': 1, 'hello': 'kitty', 'b': 2}
  • 方法五
1
2
3
import itertools
z = dict(itertools.chain(x.items(), y.items()))
print(z)

我们整体测试下性能:

1
2
3
4
5
6
import timeit
print(min(timeit.repeat(lambda: {**x, **y})))
print(min(timeit.repeat(lambda: dict(x, **y))))
print(min(timeit.repeat(lambda: merge_two_dicts(x, y))))
print(min(timeit.repeat(lambda: {k: v for d in (x, y) for k, v in d.items()} )))
print(min(timeit.repeat(lambda: dict(itertools.chain(x.items(), y.items())))))

输出:

1
2
3
4
5
0.19487747
0.327472647
0.35291755400000024
0.6816483720000006
0.7352408490000002

可以看出性能上, 方法一性能最好,方法五性能最差。 以上在 python3.7 测试通过。

Rating: