Python 字典 update() 方法

描述

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

用法與 Python dict() 函數類似。python

語法

update() 方法語法:函數

D.update(key/value)

參數

  • key/value -- 用於更新字典的鍵/值對,此處能夠表示鍵/值對的方法有不少,請看實例。

返回值

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

實例

如下實例展現了 update() 方法的使用方法:blog

# !/usr/bin/python3

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(zip(['eleven', 'twelve'], [11, 12]))  # 傳一個zip()函數
print(D)

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

以上實例輸出結果爲:three

{'one': 1, 'three': 3, 'two': 2, 'four': 4}
{'one': 1, 'four': 4, 'six': 6, 'two': 2, 'five': 5, 'three': 3}
{'one': 1, 'eight': 8, 'seven': 7, 'four': 4, 'six': 6, 'two': 2, 'five': 5, 'three': 3}
{'one': 1, 'eight': 8, 'seven': 7, 'four': 4, 'eleven': 11, 'six': 6, 'twelve': 12, 'two': 2, 'five': 5, 'three': 3}
{'four': 4, 'seven': 7, 'twelve': 12, 'six': 6, 'eleven': 11, 'three': 3, 'one': 111, 'eight': 8, 'two': 222, 'five': 5}

zip() 函數:http://www.cnblogs.com/wushuaishuai/p/7766470.htmlip

相關文章
相關標籤/搜索