update()
方法使用来自另一个字典对象或键/值对可迭代对象的元素更新字典。
示例
marks = {'Physics':67, 'Maths':87}
internal_marks = {'Practical':48}
marks.update(internal_marks)
print(marks)
# Output: {'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"}
# updates the value of key 2
d.update(d1)
print(d)
d1 = {3: "three"}
# adds element with key 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)]
。在这种情况下,元组的第一个元素用作键,第二个元素用作值。
另请阅读