Python 字典 update() 方法
update()
方法用于使用另一个字典对象或键/值对的可迭代对象更新字典。
示例
marks = {'Physics':67, 'Maths':87}
internal_marks = {'Practical':48}
marks.update(internal_marks)
print(marks)
# 输出: {'Physics': 67, 'Maths': 87, 'Practical': 48}
字典 update() 的语法
update()
的语法是:
dict.update([other])
update() 参数
update()
方法接受一个 字典 或键/值对的可迭代对象(通常是 元组)。
如果未传递参数调用 update()
,字典保持不变。
update() 的返回值
update()
方法使用字典对象或键/值对的可迭代对象更新字典。
它不返回任何值(返回 None
) 。
示例 1:update() 的工作原理
d = {1: "one", 2: "three"}
d1 = {2: "two"}
# 更新键 2 的值
d.update(d1)
print(d)
d1 = {3: "three"}
# 添加键为 3 的元素
d.update(d1)
print(d)
输出
{1: 'one', 2: 'two'}
{1: 'one', 2: 'two', 3: 'three'}
注意:如果字典中没有键,则 update()
方法会向字典添加元素。如果字典中有键,则它会用新值更新该键。
示例 2:当传递元组时的 update()
dictionary = {'x': 2}
dictionary.update([('y', 3), ('z', 0)])
print(dictionary)
输出
{'x': 2, 'y': 3, 'z': 0}
在这里,我们向 update()
函数传递了一个元组列表 [('y', 3), ('z', 0)]
。在这种情况下,元组的第一个元素用作键,第二个元素用作值。