Python Dictionary update()方法

2025年1月5日 | 阅读 2 分钟

update() 方法更新字典中的键值对。如果键值不存在,则插入;如果已存在,则更新。

它还允许通过可迭代的键值对来更新字典,例如:update(a=10,b=20) 等。

该方法的签名和示例如下。

签名

参数

other: 这是一个键值对的列表。

返回

它返回 None。

让我们通过一些 update() 方法的例子来理解它的功能。

Python 字典 update() 方法示例 1

这是一个通过传递键值对来更新字典的简单示例。此方法会更新字典。请看下面的示例。

输出

Inventory: {'Fan': 200, 'Bulb': 150, 'Led': 1000}
Updated inventory: {'Fan': 200, 'Bulb': 150, 'Led': 1000, 'cooler': 50}

Python 字典 update() 方法示例 2

如果元素(键/值)对已存在于字典中,它将覆盖它。请看下面的示例。

输出

Inventory: {'Fan': 200, 'Bulb': 150, 'Led': 1000, 'cooler': 50}
Updated inventory: {'Fan': 200, 'Bulb': 150, 'Led': 1000, 'cooler': 50}
Updated inventory: {'Fan': 200, 'Bulb': 150, 'Led': 1000, 'cooler': 150}

Python 字典 update() 方法示例 3

update() 方法还允许将可迭代的键值对作为参数。看下面的例子,向字典传递了两个值,并且字典已更新。

输出

Inventory: {'Fan': 200, 'Bulb': 150, 'Led': 1000}
Updated inventory: {'Fan': 200, 'Bulb': 150, 'Led': 1000, 'cooler': 50, 'switches': 1000}