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' } 
  
# 更新之前的字典
print("初始的字典:") 
print(Dictionary1) 
  
# 更新 key='B',对应的value
Dictionary1.update(Dictionary2) 
print("更新之后的字典:") 
print(Dictionary1)

输出:
初始的字典:
{'A':'Geeks', 'B':'For'}

更新之后的字典:
{'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'}

转载请标注:https://blog.csdn.net/Owen_goodman/article/details/115490631

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值