Python 如何更新字典的值
可以使用以下两种方法更新Python字典的值,即使用update()方法和使用方括号。
字典是Python中的键值对,以大括号括起来。键是唯一的,并且冒号将其与值分隔,逗号分隔各个项。在冒号之前的左侧是键,右侧是相应的值。
让我们首先创建一个Python字典并获取所有的值。在这里,我们在字典中包含了4个键值对并显示它们。Product,Model,Units和Available是字典的键。除了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中更新字典值的方法。
使用update()方法更新字典值
现在让我们使用update()方法来更新字典值。我们首先展示了更新前的字典,然后使用update()方法并将更新后的值作为参数传递给该方法。这里,我们只更新了两个键对应的值,即 Product 和 Model 。
示例
# 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()方法来更新字典的值。我们将使用方括号来更新单个值。在这里,我们只更新了两个键值,即 Units 和 Available 。方括号中包含了要更新的键对应的值。
示例
# 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()方法的情况下被更新,其余保持不变。