當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python Dictionary update()用法及代碼示例

Python update() 方法使用鍵值對更新字典。如果不存在,則插入鍵/值。如果它已經存在於字典中,它會更新鍵/值。

它還允許迭代鍵/值對來更新字典。如:更新(a=10,b=20)等。

下麵給出了這種方法的簽名和例子。

簽名

update([other])

參數

other:它是一個鍵/值對列表。

返回

它返回無。

讓我們看一些 update() 方法的例子來理解它的函數。

Python字典update()方法示例1

這是一個通過傳遞鍵/值對來更新字典的簡單示例。此方法更新字典。請參閱下麵的示例。

# Python dictionary update() Method
# Creating a dictionary
einventory = {'Fan':200, 'Bulb':150, 'Led':1000}
print("Inventory:",einventory)
# Calling Method
einventory.update({'cooler':50})
print("Updated inventory:",einventory)

輸出:

Inventory:{'Fan':200, 'Bulb':150, 'Led':1000}
Updated inventory:{'Fan':200, 'Bulb':150, 'Led':1000, 'cooler':50}

Python字典update()方法示例2

如果元素(鍵/值)對已經存在於字典中,它將覆蓋它。請參閱下麵的示例。

# Python dictionary update() Method
# Creating a dictionary
einventory = {'Fan':200, 'Bulb':150, 'Led':1000,'cooler':50}
print("Inventory:",einventory)
# Calling Method
einventory.update({'cooler':50})
print("Updated inventory:",einventory)
einventory.update({'cooler':150})
print("Updated inventory:",einventory)

輸出:

Inventory:{'Fan':200, 'Bulb':150, 'Led':1000, 'cooler':50}
Updated inventory:{'Fan':200, 'Bulb':150, 'Led':1000, 'cooler':50}
Updated inventory:{'Fan':200, 'Bulb':150, 'Led':1000, 'cooler':150}

Python字典update()方法示例3

update() 方法還允許可迭代的鍵/值對作為參數。請看,下麵的示例將兩個值傳遞給字典並進行更新。

# Python dictionary update() Method
# Creating a dictionary
einventory = {'Fan':200, 'Bulb':150, 'Led':1000}
print("Inventory:",einventory)
# Calling Method
einventory.update(cooler=50,switches=1000)
print("Updated inventory:",einventory)

輸出:

Inventory:{'Fan':200, 'Bulb':150, 'Led':1000}
Updated inventory:{'Fan':200, 'Bulb':150, 'Led':1000, 'cooler':50, 'switches':1000}






相關用法


注:本文由純淨天空篩選整理自 Python Dictionary update() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。