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}

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

无涯教程网

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

来源:LearnFk无涯教程网

# 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}

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

技术教程推荐

Vue开发实战 -〔唐金州〕

Node.js开发实战 -〔杨浩〕

Go 并发编程实战课 -〔晁岳攀(鸟窝)〕

零基础实战机器学习 -〔黄佳〕

徐昊 · TDD项目实战70讲 -〔徐昊〕

超级访谈:对话汤峥嵘 -〔汤峥嵘〕

Vue 3 企业级项目实战课 -〔杨文坚〕

B端产品经理入门课 -〔董小圣〕

工程师个人发展指南 -〔李云〕

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