如何更新 Python 字典的值?


可以使用以下兩種方式更新Python 字典的值,即使用update() 方法,以及使用方括號。

字典在Python中表示鍵值對,用花括號括起來。鍵是唯一的,冒號將其與值分隔開,而逗號分隔專案。其中,冒號左側是鍵,右側是對應的值。

讓我們首先建立一個 Python 字典並獲取所有值。這裡,我們在字典中包含了 4 個鍵值對並顯示它們。產品、型號、單位可用是字典的鍵。除了單位鍵之外,所有鍵都具有字串值 -

示例

# Creating a Dictionary with 4 key-value pairs myprod = { "Product":"Mobile", "Model": "XUT", "Units": 120, "Available": "Yes" } # Displaying the Dictionary print(myprod) # Displaying individual values print("Product = ",myprod["Product"]) print("Model = ",myprod["Model"]) print("Units = ",myprod["Units"]) print("Available = ",myprod["Available"])

輸出

{'Product': 'Mobile', 'Model': 'XUT', 'Units': 120, 'Available': 'Yes'}
Product = Mobile
Model = XUT
Units = 120
Available = Yes

上面,我們顯示了字典中 4 個鍵值對,其中包含產品資訊。現在,我們將看到在 Python 中更新字典值的兩種方法。

使用 update 方法更新字典

現在讓我們使用update()方法更新字典值。我們首先在更新值之前顯示了字典。之後,使用update(),並將更新後的值作為方法的引數。這裡,我們只更新了兩個鍵值,即產品型號 -

示例

# Creating a Dictionary with 4 key-value pairs myprod = { "Product":"Mobile", "Model": "XUT", "Units": 120, "Available": "Yes" } # Displaying the Dictionary print("Dictionary = \n",myprod) print("Product = ",myprod["Product"]) print("Model = ",myprod["Model"]) # Updating Dictionary Values myprod.update({"Product":"SmartTV","Model": "PHRG6",}) # Displaying the Updated Dictionary print("\nUpdated Dictionary = \n",myprod) print("Updated Product = ",myprod["Product"]) print("Updated Model = ",myprod["Model"])

輸出

Dictionary = 
 {'Product': 'Mobile', 'Model': 'XUT', 'Units': 120, 'Available': 'Yes'}
Product =  Mobile
Model =  XUT

Updated Dictionary = 
 {'Product': 'SmartTV', 'Model': 'PHRG6', 'Units': 120, 'Available': 'Yes'}
Updated Product =  SmartTV
Updated Model =  PHRG6

在輸出中,我們可以看到使用 updated() 方法更新的前兩個值,其餘值保持不變。

使用方括號更新字典

這是另一個程式碼。現在讓我們在不使用update()方法的情況下更新字典值。我們將使用方括號更新各個值。這裡,我們只更新了兩個鍵值,即單位可用。方括號包含要更新的值對應的鍵 -

示例

# Creating a Dictionary with 4 key-value pairs myprod = { "Product":"Mobile", "Model": "XUT", "Units": 120, "Available": "Yes" } # Displaying the Dictionary print("Dictionary = \n",myprod) print("Product = ",myprod["Product"]) print("Model = ",myprod["Model"]) # Updating Dictionary Values myprod["Units"] = 170 myprod["Available"] = "No" # Displaying the Updated Dictionary print("\nUpdated Dictionary = \n",myprod) print("Updated Units = ",myprod["Units"]) print("Updated Availability = ",myprod["Available"])

輸出

Dictionary = 
 {'Product': 'Mobile', 'Model': 'XUT', 'Units': 120, 'Available': 'Yes'}
Product =  Mobile
Model =  XUT

Updated Dictionary = {'Product': 'Mobile', 'Model': 'XUT', 'Units': 170, 'Available': 'No'}
Updated Units =  170
Updated Availability =  No

在輸出中,我們可以看到最後兩個值在不使用update()方法的情況下更新,其餘值保持不變。

更新於: 2023年8月23日

70K+ 瀏覽量

啟動您的職業生涯

透過完成課程獲得認證

開始學習
廣告