Python dict.update() 方法用于把另一个字典(或键值对)合并进来,同键覆盖。
语法
d.update(other_dict)
d.update(key=value, ...)参数
另一个字典,或关键字参数,或 (key, value) 对的可迭代对象。
返回值
无返回值(返回 None)。原地合并,同键被覆盖。
示例
a = {"x": 1, "y": 2}
b = {"y": 100, "z": 3}
a.update(b) # b 合入 a,y 被覆盖
print(a) # {'x': 1, 'y': 100, 'z': 3}
# 关键字参数形式
cfg = {}
cfg.update(debug=True, port=8080)
print(cfg) # {'debug': True, 'port': 8080}
# 合并但保留原字典
c = {"m": 1}
d = {"n": 2}
merged = c | d # Python 3.9+
print(merged) # {'m': 1, 'n': 2}输出:
{'x': 1, 'y': 100, 'z': 3}
{'debug': True, 'port': 8080}
{'m': 1, 'n': 2}注意事项
update 原地修改返回 None。同键以后面的为准。想返回新字典用 | 或先 copy。