Python 中的 update() 函数用于从键/值对可迭代对象或从另一个字典对象更新字典。如果键不在字典中,它会将元素插入到字典中;如果键已在字典中,它会用新值更新键。
dict.update([other]) #where other may be iterable object generally tuples
update() 函数接受一个参数。如果调用函数时未传递参数,则字典保持不变。
| 参数 | 描述 | 必需/可选 |
|---|---|---|
| other | 一个字典或一个包含键值对的可迭代对象,将被插入到字典中。 | 必需 |
update() 函数不返回任何值。此函数只用键/值对更新字典或在字典中插入新的键值。
x = {5: "five", 6: "one"}
y = {6: "six"}
# updates the value of key 6
x.update(y)
print(x)
y = {7: "seven"}
# adds element with key 7
x.update(y)
print(x)
输出
{5: 'five', 6: 'six'}
{5: 'five', 6: 'six', 7: 'seven'}
t = {'a': 1}
t.update(b = 2, c = 3)
print(t)
输出
{'a': 1, 'b': 2, 'c': 3}