如何更新Python字典的值?
有两种方法可以更新Python字典的值,即使用update()方法和方括号。
字典在Python中表示键值对,用花括号包含。键是唯一的,冒号将其与值分隔开,逗号将项目分隔。在冒号之前的左侧是键,右侧是其对应的值。
让我们首先创建一个Python字典并获取所有值。在这里,我们在字典中包含了4个键值对,并将它们显示出来。 Product,Model,Units 和 Available 是字典的键。除了Units键,所有值都是字符串值。
更多Python相关文章,请阅读:Python 教程
示例
# 创建一个有4个键值对的字典
myprod = {
"Product":"Mobile",
"Model": "XUT",
"Units": 120,
"Available": "Yes"
}
# 显示字典
print(myprod)
# 显示个别的值
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
以上,我们展示了Product信息中的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 using Square Brackets
myprod["Units"] = 200
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': 200, 'Available': 'No'}
Updated Units = 200
Updated Availability = No
在输出中,我们可以看到使用方括号仅更新了2个值,其余的保持不变。
# 创建一个包含4个键值对的字典
myprod = {
"Product":"Mobile",
"Model": "XUT",
"Units": 120,
"Available": "Yes"
}
# 打印字典
print("字典 = \n",myprod)
print("产品 = ",myprod["Product"])
print("型号 = ",myprod["Model"])
# 更新字典的值
myprod["Units"] = 170
myprod["Available"] = "No"
# 打印更新后的字典
print("\n更新后的字典 = \n",myprod)
print("更新后的数量 = ",myprod["Units"])
print("更新后的可用性 = ",myprod["Available"])
输出结果
字典 =
{'Product': 'Mobile', 'Model': 'XUT', 'Units': 120, 'Available': 'Yes'}
产品 = Mobile
型号 = XUT
更新后的字典 = {'Product': 'Mobile', 'Model': 'XUT', 'Units': 170, 'Available': 'No'}
更新后的数量 = 170
更新后的可用性 = No
在输出结果中,我们可以看到最后两个值被更新了,但并没有使用updated()方法,其他的值保持不变。