字典合并

列表和集合 / 字典

d1 = {1: "one"}
d2 = {2: "two"}
d3 = {3: "three"}

# | builds a new dict
d_all = d1 | d2
print(f'{d_all = }')
# d_all is {1: 'one', 2: 'two'}

# |= updates in place
d_all |= d3
print(f'{d_all = }')
# d_all is {1: 'one', 2: 'two', 3: 'three'}

# d1 is untouched
print(f'{d1 = }')
# d1 is {1: 'one'}

# The same key: the right one wins
clash = d1 | {1: "ONE"}
print(f'{clash = }')
# clash is {1: 'ONE'}