如何更新 Python 字典的值?

programmingpythonserver side programming更新于 2025/1/17 2:20:17

可以使用以下两种方式更新 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() 并将更新的值作为方法的参数放置。在这里,我们只更新了两个键值,即 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() 方法就进行了更新,其余值保持不变。


相关文章


有用资源