Python 简明教程

Python - Change Dictionary Items

Change Dictionary Items

在 Python 中更改字典项是指修改与字典中特定键关联的值。这可能涉及更新现有键的值,添加新的键值对,或从字典中删除键值对。

Changing dictionary items in Python refers to modifying the values associated with specific keys within a dictionary. This can involve updating the value of an existing key, adding a new key-value pair, or removing a key-value pair from the dictionary.

字典是可变的,这意味着在创建字典后可以修改其内容。

Dictionaries are mutable, meaning their contents can be modified after they are created.

Modifying Dictionary Values

修改 Python 字典中的值是指更改与现有键关联的值。要实现此目的,您可以直接向该键分配一个新值。

Modifying values in a Python dictionary refers to changing the value associated with an existing key. To achieve this, you can directly assign a new value to that key.

Example

在以下示例中,我们定义了一个名为“person”的字典,其键为“name”、“age”和“city”,及其相应的值。然后,我们将与键“age”关联的值修改为 26:

In the following example, we are defining a dictionary named "person" with keys 'name', 'age', and 'city' and their corresponding values. Then, we modify the value associated with the key 'age' to 26 −

# Initial dictionary
person = {'name': 'Alice', 'age': 25, 'city': 'New York'}
# Modifying the value associated with the key 'age'
person['age'] = 26
print(person)

它将生成如下输出:

It will produce the following output −

{'name': 'Alice', 'age': 26, 'city': 'New York'}

Updating Multiple Dictionary Values

如果您需要一次更新字典中的多个值,可以使用 update() 方法。此方法用于使用另一个字典或键值对的 iterable 来更新字典。

If you need to update multiple values in a dictionary at once, you can use the update() method. This method is used to update a dictionary with elements from another dictionary or an iterable of key-value pairs.

update() 方法将来自提供的字典或 iterable 的键值对添加到原始字典,如果它们已存在于原始字典中,则使用新值覆盖任何现有键。

The update() method adds the key-value pairs from the provided dictionary or iterable to the original dictionary, overwriting any existing keys with the new values if they already exist in the original dictionary.

Example

在以下示例中,我们使用 update() 方法来修改“persons”字典中与键“age”和“city”关联的值:

In the example below, we are using the update() method to modify the values associated with the keys 'age' and 'city' in the 'persons' dictionary −

# Initial dictionary
person = {'name': 'Alice', 'age': 25, 'city': 'New York'}
# Updating multiple values
person.update({'age': 26, 'city': 'Los Angeles'})
print(person)

我们得到了如下输出 −

We get the output as shown below −

{'name': 'Alice', 'age': 26, 'city': 'Los Angeles'}

Conditional Dictionary Modification

Python 字典中的条件修改是指仅满足特定条件时才更改与键关联的值。

Conditional modification in a Python dictionary refers to changing the value associated with a key only if a certain condition is met.

您可以在修改与键关联的值之前使用 if 语句来检查某个条件是否为 真。

You can use an if statement to check whether a certain condition is true before modifying the value associated with a key.

Example

在本例中,我们有条件地将与键 'age' 关联的值修改为 '26',如果 'persons' 字典中当前的值为 '25' −

In this example, we conditionally modify the value associated with the key 'age' to '26' if the current value is '25' in the 'persons' dictionary −

# Initial dictionary
person = {'name': 'Alice', 'age': 25, 'city': 'New York'}
# Conditionally modifying the value associated with 'age'
if person['age'] == 25:
   person['age'] = 26
print(person)

获得的输出如下所示 −

The output obtained is as shown below −

{'name': 'Alice', 'age': 26, 'city': 'New York'}

Modify Dictionary by Adding New Key-Value Pairs

向 Python 字典添加新的键值对是指将新键与其对应的值一起插入字典中。

Adding new key-value pairs to a Python dictionary refers to inserting a new key along with its corresponding value into the dictionary.

此过程允许您通过根据需要包括附加信息来动态扩展存储在字典中的数据。

This process allows you to dynamically expand the data stored in the dictionary by including additional information as needed.

Example: Using Assignment Operator

您可以通过直接将值分配给新键来向字典添加新的键值对,如下所示。在下面的示例中,键 'city' 及其值 'New York' 已添加到 'person' 字典 −

You can add a new key-value pair to a dictionary by directly assigning a value to a new key as shown below. In the example below, the key 'city' with the value 'New York' is added to the 'person' dictionary −

# Initial dictionary
person = {'name': 'Alice', 'age': 25}
# Adding a new key-value pair 'city': 'New York'
person['city'] = 'New York'
print(person)

产生的结果如下 −

The result produced is as follows −

{'name': 'Alice', 'age': 25, 'city': 'New York'}

Example: Using the setdefault() Method

您可以使用 setdefault() 方法向字典添加新的键值对,前提是键不存在。

You can use the setdefault() method to add a new key-value pair to a dictionary if the key does not already exist.

在本例中,setdefault() 方法仅当键 'city' 不存在于 'person' 字典中时才使用值 'New York' 添加新键 'city' −

In this example, the setdefault() method adds the new key 'city' with the value 'New York' to the 'person' dictionary only if the key 'city' does not already exist −

# Initial dictionary
person = {'name': 'Alice', 'age': 25}
# Adding a new key-value pair 'city': 'New York'
person.setdefault('city', 'New York')
print(person)

以下是上面代码的输出: -

Following is the output of the above code −

{'name': 'Alice', 'age': 25, 'city': 'New York'}

Modify Dictionary by Removing Key-Value Pairs

删除 Python 字典中的键值对是指从字典中删除特定键及其对应的值。

Removing key-value pairs from a Python dictionary refers to deleting specific keys along with their corresponding values from the dictionary.

这个过程允许你基于想要移除的键,从字典中有选择地删除数据。

This process allows you to selectively remove data from the dictionary based on the keys you want to eliminate.

Example: Using the del Statement

你可以使用 del 语句从字典中移除特定键值对。在此示例中,del 语句将键 'age' 连同其关联的值从 'person' 字典中移除 −

You can use the del statement to remove a specific key-value pair from a dictionary. In this example, the del statement removes the key 'age' along with its associated value from the 'person' dictionary −

# Initial dictionary
person = {'name': 'Alice', 'age': 25, 'city': 'New York'}
# Removing the key-value pair associated with the key 'age'
del person['age']
print(person)

以上代码的输出如下所示 −

Output of the above code is as shown below −

{'name': 'Alice', 'city': 'New York'}

Example: Using the pop() Method

你也可以使用 pop() 方法从字典中移除特定键值对,并返回与移除键关联的值。

You can also use the pop() method to remove a specific key-value pair from a dictionary and return the value associated with the removed key.

在这里,pop() 方法将键 'age' 连同其关联的值从 'person' 字典中移除 −

In here, the pop() method removes the key 'age' along with its associated value from the 'person' dictionary −

# Initial dictionary
person = {'name': 'Alice', 'age': 25, 'city': 'New York'}
# Removing the key-value pair associated with the key 'age'
removed_age = person.pop('age')

print(person)
print("Removed age:", removed_age)

它将生成如下输出:

It will produce the following output −

{'name': 'Alice', 'city': 'New York'}
Removed age: 25

Example: Using the popitem() Method

你也可以使用 popitem() 方法从字典中移除最后一个键值对并以元组的形式返回它。

You can use the popitem() method as well to remove the last key-value pair from a dictionary and return it as a tuple.

现在,popitem() 方法从 'person' 字典中移除最后一个键值对并以元组的形式返回它 −

Now, the popitem() method removes the last key-value pair from the 'person' dictionary and returns it as a tuple −

# Initial dictionary
person = {'name': 'Alice', 'age': 25, 'city': 'New York'}
# Removing the last key-value pair
removed_item = person.popitem()

print(person)
print("Removed item:", removed_item)

我们得到了如下输出 −

We get the output as shown below −

{'name': 'Alice', 'age': 25}
Removed item: ('city', 'New York')