如何更新 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+ 浏览量

启动您的职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.