Python3 中的 dict.update(dict2)函数

首页 / Python3入门教程 / Python3 中的 dict.update(dict2)函数

Python update()方法使用键和值对更新字典。如果不存在,则会插入键/值。如果字典中已经存在键/值,它将更新键/值。

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

dict.update - 语法

update([other])

dict.update - 参数

other:这是键/值对的列表。

dict.update - 返回

它返回None。

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

无涯教程网

# Python dictionary update() Method
# Creating a dictionary
einventory = {'Fan': 200, 'Bulb':150, 'Led':1000}
print("Inventory:",einventory)
# Calling Method
einventory.update({'cooler':50})
print("Updated inventory:",einventory)

输出

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

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

# Python dictionary update() Method
# Creating a dictionary
einventory = {'Fan': 200, 'Bulb':150, 'Led':1000,'cooler':50}
print("Inventory:",einventory)
# Calling Method
einventory.update({'cooler':50})
print("Updated inventory:",einventory)
einventory.update({'cooler':150})
print("Updated inventory:",einventory)

输出

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}

update()方法还允许将可迭代的键/值对用作参数。请参阅,下面的示例将两个值传递给字典并对其进行更新。

# Python dictionary update() Method
# Creating a dictionary
einventory = {'Fan': 200, 'Bulb':150, 'Led':1000}
print("Inventory:",einventory)
# Calling Method
einventory.update(cooler=50,switches=1000)
print("Updated inventory:",einventory)

输出

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

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

趣谈网络协议 -〔刘超〕

Linux性能优化实战 -〔倪朋飞〕

Netty源码剖析与实战 -〔傅健〕

恋爱必修课 -〔李一帆〕

数据分析思维课 -〔郭炜〕

玩转Vue 3全家桶 -〔大圣〕

Kubernetes入门实战课 -〔罗剑锋〕

手把手教你落地DDD -〔钟敬〕

Rust 语言从入门到实战 -〔唐刚〕

好记忆不如烂笔头。留下您的足迹吧 :)