Python 字典 update()

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)]。在这种情况下,元组的第一个元素用作键,第二个元素用作值。


另请阅读

在我们结束之前,让我们测试一下你对 Python 字典 update() 的知识!你能解决以下挑战吗?

挑战

编写一个函数来合并两个字典。

  • 返回合并后的字典。
  • 例如,对于输入 {'a': 1, 'b': 2}{'c': 3, 'd': 4},输出应为 {'a': 1, 'b': 2, 'c': 3, 'd': 4}
你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战