1、 Python 3.9.0 或更高版本使用|
x = {'C': 11, 'Java': 22}
y = {'Python': 33, 'CJavaPy': 44}
z = x | y
print(z)
注意:TypeError: unsupported operand type(s) for |: 'dict' and 'dict'
这个错误原因是Python是Python 3.9.0之前版本,不支持这个语法。
2、Python 3.5 或更高版本使用**
x = {'C': 11, 'Java': 22}
y = {'Python': 33, 'CJavaPy': 44}
z = {**x, **y}
print(z)
3、Python 2或 3.4及更低版本使用自定函数
def merge_two_dicts(x, y):
z = x.copy()
z.update(y)
return z
x = {'C': 11, 'Java': 22}
y = {'Python': 33, 'CJavaPy': 44}
print(merge_two_dicts(x , y))
4、合并多个字典(dict)
def merge_dicts(*dict_args): result = {} for dictionary in dict_args: result.update(dictionary) return result x = {'C': 11, 'Java': 22} y = {'Python': 33, 'CJavaPy': 44} z ={'www.cjavapy.com':55,'Linux':66} print(merge_dicts(x , y, z))
5、性能测试
from timeit import repeat from itertools import chain x = dict.fromkeys('https://www.cjavapy.com') y = dict.fromkeys('javascript') def merge_dicts(*dict_args): result = {} for dictionary in dict_args: result.update(dictionary) return result print(min(repeat(lambda: {**x, **y},number=1))) print(min(repeat(lambda: merge_dicts(x, y),number=1))) #min(repeat(lambda: x | y)) #python 3.9.0及以上版本 print(min(repeat(lambda: {k: v for d in (x, y) for k, v in d.items()},number=1))) print(min(repeat(lambda: dict(chain(x.items(), y.items())),number=1))) print(min(repeat(lambda: dict(item for d in (x, y) for item in d.items()),number=1)))