python dict update_Python dict update()用法及代码示例

字典Python中的数据是一个无序的数据值集合,用于存储数据值(如Map),与其他仅将单个值作为元素的数据类型不同,Dictionary拥有key:value对。

在Python字典中,update()方法使用另一个字典对象或可迭代的键/值对中的元素更新字典。

用法: dict.update([other])

参数:此方法将字典或键/值对(通常为元组)的可迭代对象作为参数。

返回:它不返回任何值,而是使用字典对象或键/值对的可迭代对象中的元素更新字典。

范例1:用另一本词典更新。

# Python program to show working

# of update() method in Dictionary

# Dictionary with three items

Dictionary1 = { 'A':'Geeks', 'B':'For', }

Dictionary2 = { 'B':'Geeks' }

# Dictionary before Updation

print("Original Dictionary:")

print(Dictionary1)

# update the value of key 'B'

Dictionary1.update(Dictionary2)

print("Dictionary after updation:")

print(Dictionary1)

输出:

Original Dictionary:

{'A':'Geeks', 'B':'For'}

Dictionary after updation:

{'A':'Geeks', 'B':'Geeks'}

范例2:迭代更新。

# Python program to show working

# of update() method in Dictionary

# Dictionary with single item

Dictionary1 = { 'A':'Geeks'}

# Dictionary before Updation

print("Original Dictionary:")

print(Dictionary1)

# update the Dictionary with iterable

Dictionary1.update(B = 'For', C = 'Geeks')

print("Dictionary after updation:")

print(Dictionary1)

输出:

Original Dictionary:

{'A':'Geeks'}

Dictionary after updation:

{'C':'Geeks', 'B':'For', 'A':'Geeks'}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值