Python Dictionary update() 函数用法

2023-09-17 22:25:49

dict.update() 方法使用来自另一个字典或另一个可迭代对象(如具有键值对的元组)的键值对更新字典。

语法:

dict.update(iterable)

参数:

可迭代:(可选)字典或具有键、值对的可迭代对象。

返回值:

没有。

下面使用 dict.update() 方法更新字典。

romanNums = {'I':1,'III':3,'V':5}
print("Dictionary: ",romanNums)
evenRomanNums = {'II':2,'IV':4}
romanNums.update(evenRomanNums)
print("Updated Dictionary: ",romanNums)

输出:

Dictionary:  {'I': 1, 'III': 3, 'V': 5}
Updated Dictionary:  {'I': 1, 'III': 3, 'V': 5, 'II': 2, 'IV': 4}

还可以在 update() 方法中传递元组以更新字典。

romanNums = {'I':1,'III':3,'V':5}
print("Dictionary: ",romanNums)
romanNums.update((II=2,IV=4))
print("Updated Dictionary: ",romanNums)

输出:

Dictionary:  {'I': 1, 'III': 3, 'V': 5}
Updated Dictionary:  {'I': 1, 'III': 3, 'V': 5, 'II': 2, 'IV': 4}

如果未传递任何参数,则字典保持不变。

romanNums = {'I':1,'III':3,'V':5}
print("Dictionary: ",romanNums)
romanNums.update()
print("Updated Dictionary: ",romanNums)

输出:

Dictionary:  {'I': 1, 'II': 2 }
Updated Dictionary:  {'I': 1, 'II': 2 }