如何在 Python 字典中插入新的鍵/值?
要將新的鍵/值對插入到字典中,可以使用方括號和賦值運算子。此外,還可以使用update() 方法。請記住,如果鍵已存在於字典中,則其值將被更新,否則將插入新的鍵值對。
可以將字典視為一組鍵:值對,要求鍵在同一個字典中是唯一的。字典中的每個鍵都用冒號(:)與它的值分隔開,各個項用逗號分隔,整個字典用花括號括起來。
讓我們首先建立一個 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 中更新字典值的兩種方法。
在字典中插入新的鍵值對
現在讓我們在字典中插入新的鍵:值。我們首先在更新值之前顯示了字典。這裡,我們插入了一個新的鍵:值對,即等級,使用賦值運算子。
示例
# Creating a Dictionary with 4 key-value pairs myprod = { "Product":"Mobile", "Model": "XUT", "Units": 120, "Available": "Yes" } # Displaying the Dictionary print("Dictionary = \n",myprod) # Inserting new key:value pair myprod["Rating"] = "A" # Displaying the Updated Dictionary with 5 key:value pairs print("\nUpdated Dictionary = \n",myprod)
輸出
Dictionary = {'Product': 'Mobile', 'Model': 'XUT', 'Units': 120, 'Available': 'Yes'} Updated Dictionary = {'Product': 'Mobile', 'Model': 'XUT', 'Units': 120, 'Available': 'Yes', 'Rating': 'A'}
上面,我們將字典從 4 個鍵值對更新為 5 個鍵值對。
如果鍵已存在,則在字典中插入新的鍵值對
如果在插入新的鍵:值對時,鍵已存在,則其值將被更新。這裡,我們嘗試新增實際上已經存在的單位鍵。因此,只有值會更新為新值。
示例
# Creating a Dictionary with 4 key-value pairs myprod = { "Product":"Mobile", "Model": "XUT", "Units": 120, "Available": "Yes" } # Displaying the Dictionary print("Dictionary = \n",myprod) # Inserting a key that already exists, updates only the values myprod["Units"] = "200" # Displaying the Updated Dictionary print("\nUpdated Dictionary = \n",myprod)
輸出
Dictionary = {'Product': 'Mobile', 'Model': 'XUT', 'Units': 120, 'Available': 'Yes'} Updated Dictionary = {'Product': 'Mobile', 'Model': 'XUT', 'Units': '200', 'Available': 'Yes'}
使用 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) # Updating Dictionary Values myprod.update({"Grade":"A","Tax":"Yes"}) # Displaying the Updated Dictionary print("\nUpdated Dictionary = \n",myprod)
輸出
Dictionary = {'Product': 'Mobile', 'Model': 'XUT', 'Units': 120, 'Available': 'Yes'} Updated Dictionary = {'Product': 'Mobile', 'Model': 'XUT', 'Units': 120, 'Available': 'Yes', 'Grade': 'A', 'Tax': 'Yes'}
廣告