x = {'a': 1, 'b': 2} y = {'b': 3, 'c': 4} z = {**x, **y} print(z) # 输出: {'a': 1, 'b': 3, 'c': 4}
Python 2 或 3.4 及以下版本
在Python 2或3.4及以下版本中,需要自定义函数来合并两个字典。示例代码如下:
1 2 3 4 5 6 7 8 9
defmerge_two_dicts(x, y): z = x.copy() # 复制x字典 z.update(y) # 更新z字典,用y字典的键值对覆盖z中相同键的值 return z
x = {'a': 1, 'b': 2} y = {'b': 3, 'c': 4} z = merge_two_dicts(x, y) print(z) # 输出: {'a': 1, 'b': 3, 'c': 4}
核心代码
合并任意数量的字典
可以编写一个函数来合并任意数量的字典,示例代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
defmerge_dicts(*dict_args): """ 合并任意数量的字典,后面字典的键值对会覆盖前面字典中相同键的值 """ result = {} for dictionary in dict_args: result.update(dictionary) return result
a = {'a': 1} b = {'b': 2} c = {'c': 3} z = merge_dicts(a, b, c) print(z) # 输出: {'a': 1, 'b': 2, 'c': 3}
递归合并嵌套字典
如果需要递归合并嵌套字典,可以使用以下代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
from copy import deepcopy
defdict_of_dicts_merge(x, y): z = {} overlapping_keys = x.keys() & y.keys() for key in overlapping_keys: z[key] = dict_of_dicts_merge(x[key], y[key]) for key in x.keys() - overlapping_keys: z[key] = deepcopy(x[key]) for key in y.keys() - overlapping_keys: z[key] = deepcopy(y[key]) return z
from timeit import repeat from itertools import chain
x = dict.fromkeys('abcdefg') y = dict.fromkeys('efghijk')
defmerge_two_dicts(x, y): z = x.copy() z.update(y) return z
print(min(repeat(lambda: {**x, **y}))) print(min(repeat(lambda: merge_two_dicts(x, y)))) print(min(repeat(lambda: {k: v for d in (x, y) for k, v in d.items()}))) print(min(repeat(lambda: dict(chain(x.items(), y.items()))))) print(min(repeat(lambda: dict(item for d in (x, y) for item in d.items()))))
在Python 3.8.1中,测试结果表明 {**x, **y} 和 x | y(Python 3.9+) 通常是最快的方法。
代码可读性
代码的可读性也很重要。对于简单的合并需求,使用 {**x, **y} 或 x | y 是简洁且易于理解的。对于需要自定义合并逻辑的场景,编写自定义函数可以提高代码的可读性和可维护性。