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