python 字典中的Update()函數


簡介 
Python 字典 update() 方法用於更新字典中的鍵/值對,可以修改存在的鍵對應的值,也可以添加新的鍵/值對到字典中。

語法 
d.update(e)

參數說明 
將e中鍵-值對添加到字典d中,e可能是字典,也可能是鍵-值對序列。詳見實例。

返回值 
該方法沒有任何返回值。

實例 
以下實例展示了 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(([‘nice’,9],[‘ten’,10])) # 傳一個包含一個或多個列表的元組 
print(d)

d.update(zip([‘eleven’,’twelve’],[11,12])) # 傳一個zip()函數 
print(d)

d.update(one=111,two=222) # 使用以上任意方法修改存在的鍵對應的值 
print(d)

以上實例輸出結果為:

{‘one’: 1, ‘four’: 4, ‘three’: 3, ‘two’: 2} 
{‘one’: 1, ‘four’: 4, ‘three’: 3, ‘five’: 5, ‘two’: 2, ‘six’: 6} 
{‘seven’: 7, ‘one’: 1, ‘four’: 4, ‘three’: 3, ‘five’: 5, ‘two’: 2, ‘six’: 6, ‘eight’: 8} 
{‘seven’: 7, ‘one’: 1, ‘four’: 4, ‘three’: 3, ‘ten’: 10, ‘five’: 5, ‘nice’: 9, ‘two’: 2, ‘six’: 6, ‘eight’: 8} 
{‘one’: 1, ‘four’: 4, ‘three’: 3, ‘twelve’: 12, ‘ten’: 10, ‘seven’: 7, ‘six’: 6, ‘eleven’: 11, ‘two’: 2, ‘nice’: 9, ‘five’: 5, ‘eight’: 8} 
{‘one’: 111, ‘four’: 4, ‘three’: 3, ‘twelve’: 12, ‘ten’: 10, ‘seven’: 7, ‘six’: 6, ‘eleven’: 11, ‘two’: 222, ‘nice’: 9, ‘five’: 5, ‘eight’: 8}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM