如何将新键/值插入 Python 字典?

programmingpythonserver side programming更新于 2025/1/21 8:44:17

要将新键/值插入字典,请使用方括号和赋值运算符。这样,也可以使用 update() 方法。请记住,如果键已存在于字典中,则其值将更新,否则将插入新对。

将字典视为一组 键:值 对,要求键是唯一的(在一个字典内)。字典中的每个键都用冒号 (:) 与其值分隔,项用逗号分隔,整个字典用花括号括起来。

让我们首先创建一个 Python 字典并获取所有值。在这里,我们在字典中包含了 4 个 键-值 对并显示它们。产品、型号、单位 和 可用 是字典的键。除 Units 键外,所有键都具有字符串值 −

示例

# 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 中更新字典值的两种方法。

在字典中插入新的键值对

现在让我们将新的 key:value 插入字典中。在更新值之前,我们首先显示了字典。在这里,我们使用赋值运算符插入了一个新的 key:value 对,即 Grade -

示例

# 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 个 key:value 更新为 5 个 key:value 对。

如果键已存在,则在字典中插入新的键值对

如果在插入新的 key:value 对时,键已存在,则值将更新。这里,我们尝试添加实际存在的 Units 键。因此,只有值会使用新值进行更新 −

示例

# 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() 方法插入新的键值对。在该方法下添加您想要添加的键值对。这将插入新的对 Ratings 和 Tax −

示例

# 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'}


相关文章


有用资源