Python3 中的 dict.update(dict2)函数

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

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

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

链接:https://www.learnfk.comhttps://www.learnfk.com/python3/python-dictionary-update-method.html

来源:LearnFk无涯教程网

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}

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

技术教程推荐

从0开始学大数据 -〔李智慧〕

数据分析实战45讲 -〔陈旸〕

深入浅出计算机组成原理 -〔徐文浩〕

编辑训练营 -〔总编室〕

Web安全攻防实战 -〔王昊天〕

大厂广告产品心法 -〔郭谊〕

现代React Web开发实战 -〔宋一玮〕

零基础GPT应用入门课 -〔林健(键盘)〕

给程序员的写作课 -〔高磊〕

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