1. 程式人生 > >Python 字典 update() 方法

Python 字典 update() 方法

更新 shu lan one 函數 htm log 參數 實例

描述

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

用法與 Python dict() 函數相似。

語法

update() 方法語法:

D.update(key/value)

參數

  • key/value -- 用於更新字典的鍵/值對,此處可以表示鍵/值對的方法有很多,請看實例。

返回值

該方法沒有任何返回值。

實例

以下實例展示了 update() 方法的使用方法:

# !/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)

以上實例輸出結果為:

{‘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.html

Python 字典 update() 方法