Python字典update()方法

目录

描述
语法
参数
返回值
实例

正文

描述

Python 字典 update() 方法用于更新字典中的键/值对,可以修改存在的键对应的值,也可以添加新的键/值对到字典中。

用法与 Python dict() 函数相似。

语法

update() 方法语法:

D.update(key/value)
参数

key/value – 用于更新字典的键/值对,此处可以表示键/值对的方法有很多,请看实例。

返回值

该方法没有任何返回值。

实例

以下实例展示了 update() 方法的使用方法:

D = {'one': 1, 'two': 2}
 
D.update({'three': 3, 'four': 4})  # 传一个字典
print(D)
 
D.update(five=5, six=6)  # 传关键字
print(D)
 
D.update([('seven', 7), ('eight', 8)])  # 传一个包含一个或多个元祖的列表
print(D)
 
D.update(zip(['eleven', 'twelve'], [11, 12]))  # 传一个zip()函数
print(D)
 
D.update(one=111, two=222)  # 使用以上任意方法修改存在的键对应的值
print(D)

以上实例输出结果为:

{'one': 1, 'three': 3, 'two': 2, 'four': 4}
{'one': 1, 'four': 4, 'six': 6, 'two': 2, 'five': 5, 'three': 3}
{'one': 1, 'eight': 8, 'seven': 7, 'four': 4, 'six': 6, 'two': 2, 'five': 5, 'three': 3}
{'one': 1, 'eight': 8, 'seven': 7, 'four': 4, 'eleven': 11, 'six': 6, 'twelve': 12, 'two': 2, 'five': 5, 'three': 3}
{'four': 4, 'seven': 7, 'twelve': 12, 'six': 6, 'eleven': 11, 'three': 3, 'one': 111, 'eight': 8, 'two': 222, 'five': 5}

zip() 函数:http://www.cnblogs.com/wushuaishuai/p/7766470.html

  • 10
    点赞
  • 51
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值