Python 简明教程

Python - Add Dictionary Items

Add Dictionary Items

在 Python 中添加字典项是指向现有字典中插入新的键值对。字典是可变的数据结构,其中存储键值对集合,每个键都与相应的值关联。

Adding dictionary items in Python refers to inserting new key-value pairs into an existing dictionary. Dictionaries are mutable data structures that store collections of key-value pairs, where each key is associated with a corresponding value.

向字典中添加项目允许在程序执行期间根据需要动态更新和扩展其内容。

Adding items to a dictionary allows you to dynamically update and expand its contents as needed during program execution.

我们可以使用以下各种方式在 Python 中添加字典项:

We can add dictionary items in Python using various ways such as −

  1. Using square brackets

  2. Using the update() method

  3. Using a comprehension

  4. Using unpacking

  5. Using the Union Operator

  6. Using the |= Operator

  7. Using setdefault() method

  8. Using collections.defaultdict() method

Add Dictionary Item Using Square Brackets

Python 中的方括号 [] 用于通过索引和切片操作访问序列(如列表和字符串)中的元素。此外,使用字典时,方括号用于指定访问或修改关联值的键。

The square brackets [] in Python is used to access elements in sequences like lists and strings through indexing and slicing operations. Additionally, when working with dictionaries, square brackets are used to specify keys for accessing or modifying associated values.

你可以通过在方括号中指定键并为其分配值来向字典添加项目。如果该键已存在于字典对象中,则其值将更新为 val。如果该键不存在于字典中,则将添加新的键值对。

You can add items to a dictionary by specifying the key within square brackets and assigning a value to it. If the key is already present in the dictionary object, its value will be updated to val. If the key is not present in the dictionary, a new key-value pair will be added.

Example

在此示例中,我们创建一个名为“marks”的字典,其中键表示名称及其相应的整数值。然后,我们使用方括号表示法将新的键值对“Kavta”:58 添加到字典中:

In this example, we are creating a dictionary named "marks" with keys representing names and their corresponding integer values. Then, we add a new key-value pair 'Kavta': 58 to the dictionary using square bracket notation −

marks = {"Savita":67, "Imtiaz":88, "Laxman":91, "David":49}
print ("Initial dictionary: ", marks)
marks['Kavya'] = 58
print ("Dictionary after new addition: ", marks)

它将生成如下输出:

It will produce the following output −

Initial dictionary:  {'Savita': 67, 'Imtiaz': 88, 'Laxman': 91, 'David': 49}
Dictionary after new addition:  {'Savita': 67, 'Imtiaz': 88, 'Laxman': 91, 'David': 49, 'Kavya': 58}

Add Dictionary Item Using the update() Method

Python 字典中的 update() 方法用于将另一个字典或键值对的可迭代对象的内容合并到当前字典中。它添加或更新键值对,确保使用新值更新现有键,并将新键添加到字典中。

The update() method in Python dictionaries is used to merge the contents of another dictionary or an iterable of key-value pairs into the current dictionary. It adds or updates key-value pairs, ensuring that existing keys are updated with new values and new keys are added to the dictionary.

你可以使用 update() 方法通过传递另一个字典或键值对的可迭代对象来向字典添加多个项目。

You can add multiple items to a dictionary using the update() method by passing another dictionary or an iterable of key-value pairs.

Example

在以下示例中,我们使用 update() 方法将多个新的键值对“Kavya”:58 和“Mohan”:98 添加到字典“marks”中:

In the following example, we use the update() method to add multiple new key-value pairs 'Kavya': 58 and 'Mohan': 98 to the dictionary 'marks' −

marks = {"Savita":67, "Imtiaz":88}
print ("Initial dictionary: ", marks)
marks.update({'Kavya': 58, 'Mohan': 98})
print ("Dictionary after new addition: ", marks)

我们得到了如下输出 −

We get the output as shown below −

Initial dictionary:  {'Savita': 67, 'Imtiaz': 88}
Dictionary after new addition:  {'Savita': 67, 'Imtiaz': 88, 'Kavya': 58, 'Mohan': 98}

Add Dictionary Item Using Unpacking

在 Python 中解包是指从集合中提取各个元素(例如,列表、元组或字典),并在单个语句中将它们分配给变量。这可以使用 * operator for iterables like lists and tuples, and the * * 算符来完成 dictionaries

Unpacking in Python refers to extracting individual elements from a collection, such as a list, tuple, or dictionary, and assigning them to variables in a single statement. This can be done using the operator for iterables like lists and tuples, and the * operator for dictionaries.

我们可以通过使用 ** 解包算符将两个或两个以上的字典进行合并来添加字典项。

We can add dictionary items using unpacking by combining two or more dictionaries with the ** unpacking operator.

Example

在下面的示例中,我们初始化了名为“marks”和“marks1”的两个字典,它们都包含名称及其相应的整数值。然后,我们通过使用字典解包将“marks”和“marks1”合并来创建一个新字典“newmarks”:

In the example below, we are initializing two dictionaries named "marks" and "marks1", both containing names and their corresponding integer values. Then, we create a new dictionary "newmarks" by merging "marks" and "marks1" using dictionary unpacking −

marks = {"Savita":67, "Imtiaz":88, "Laxman":91, "David":49}
print ("marks dictionary before update: \n", marks)
marks1 = {"Sharad": 51, "Mushtaq": 61, "Laxman": 89}
newmarks = {**marks, **marks1}
print ("marks dictionary after update: \n", newmarks)

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

Following is the output of the above code −

marks dictionary before update:
 {'Savita': 67, 'Imtiaz': 88, 'Laxman': 91, 'David': 49}
marks dictionary after update:
 {'Savita': 67, 'Imtiaz': 88, 'Laxman': 89, 'David': 49, 'Sharad': 51, 'Mushtaq': 61}

Add Dictionary Item Using the Union Operator (|)

Python 中的并集算符,由 | 符号表示,用于将两个集合的元素合并到一个新集合中,该新集合包含来自两个集合的所有唯一元素。它还可以在 Python 3.9 及更高版本中与字典一起使用,以合并两个字典的内容。

The union operator in Python, represented by the | symbol, is used to combine the elements of two sets into a new set that contains all the unique elements from both sets. It can also be used with dictionaries in Python 3.9 and later to merge the contents of two dictionaries.

我们可以通过将两个字典合并到一个新字典中来添加字典项,其中包括来自两个字典的所有键值对。

We can add dictionary items using the union operator by merging two dictionaries into a new dictionary, which includes all key-value pairs from both dictionaries.

Example

在这个示例中,我们使用 | 算符将“marks”和“marks1”字典进行合并,其中在出现重复键时,“marks1”中的值具有优先权:

In this example, we are using the | operator to combine the dictionaries "marks" and "marks1" with "marks1" values taking precedence in case of duplicate keys −

marks = {"Savita":67, "Imtiaz":88, "Laxman":91, "David":49}
print ("marks dictionary before update: \n", marks)
marks1 = {"Sharad": 51, "Mushtaq": 61, "Laxman": 89}
newmarks = marks | marks1
print ("marks dictionary after update: \n", newmarks)

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

Output of the above code is as shown below −

marks dictionary before update:
 {'Savita': 67, 'Imtiaz': 88, 'Laxman': 91, 'David': 49}
marks dictionary after update:
 {'Savita': 67, 'Imtiaz': 88, 'Laxman': 89, 'David': 49, 'Sharad': 51, 'Mushtaq': 61}

Add Dictionary Item Using the "|=" Operator

Python 中的 |= 算符是集合和字典的原地并集算符。它将左手侧的集合或字典使用右手侧的集合或字典中的元素进行更新。

The |= operator in Python is an in-place union operator for sets and dictionaries. It updates the set or dictionary on the left-hand side with elements from the set or dictionary on the right-hand side.

我们可以通过使用另一个字典中的键值对来更新现有的字典,从而使用 |= 算符添加字典项。如果存在重叠键,则右手侧字典中的值将覆盖左手侧字典中的值。

We can add dictionary items using the |= operator by updating an existing dictionary with key-value pairs from another dictionary. If there are overlapping keys, the values from the right-hand dictionary will overwrite those in the left-hand dictionary.

Example

在下面的示例中,我们使用 |= 算符使用来自“marks1”中的键值对来更新“marks”,其中在出现重复键时,“marks1”中的值具有优先权:

In the following example, we use the |= operator to update "marks" with the key-value pairs from "marks1", with values from "marks1" taking precedence in case of duplicate keys −

marks = {"Savita":67, "Imtiaz":88, "Laxman":91, "David":49}
print ("marks dictionary before update: \n", marks)
marks1 = {"Sharad": 51, "Mushtaq": 61, "Laxman": 89}
marks |= marks1
print ("marks dictionary after update: \n", marks)

下面显示了产生的输出:

The output produced is as shown below −

marks dictionary before update:
 {'Savita': 67, 'Imtiaz': 88, 'Laxman': 91, 'David': 49}
marks dictionary after update:
 {'Savita': 67, 'Imtiaz': 88, 'Laxman': 89, 'David': 49, 'Sharad': 51, 'Mushtaq': 61}

Add Dictionary Item Using the setdefault() Method

Python 中的 setdefault() 方法用于获取字典中指定键的值。如果键不存在,则它会使用指定的默认值插入该键。

The setdefault() method in Python is used to get the value of a specified key in a dictionary. If the key does not exist, it inserts the key with a specified default value.

我们可以通过显式指定键和默认值,从而使用 setdefault() 方法添加字典项。

We can add dictionary items using the setdefault() method by specifying a key and a default value.

Example

在这个示例中,我们使用 setdefault() 将键值对:“major”:“Computer Science”添加到“student”字典中:

In this example, we use the setdefault() to add the key-value pair "major": "Computer Science" to the "student" dictionary −

# Initial dictionary
student = {"name": "Alice", "age": 21}
# Adding a new key-value pair
major = student.setdefault("major", "Computer Science")
print(student)

由于键“major”不存在,因此它会使用指定的默认值添加,如下面的输出所示:

Since the key "major" does not exist, it is added with the specified default value as shown in the output below −

{'name': 'Alice', 'age': 21, 'major': 'Computer Science'}

Add Dictionary Item Using the collections.defaultdict() Method

Python 中的 collections.defaultdict() 方法是内置“dict”类的子类,它创建具有尚未设置的键的默认值的字典。它是 Python 标准库中 collections 模块的一部分。

The collections.defaultdict() method in Python is a subclass of the built-in "dict" class that creates dictionaries with default values for keys that have not been set yet. It is part of the collections module in Python’s standard library.

我们可以通过指定默认工厂,从而使用 collections.defaultdict() 方法添加字典项,该工厂确定尚未设置的键的默认值。首次访问丢失的键时,将调用默认工厂来创建默认值,并将此值插入字典中。

We can add dictionary items using the collections.defaultdict() method by specifying a default factory, which determines the default value for keys that have not been set yet. When accessing a missing key for the first time, the default factory is called to create a default value, and this value is inserted into the dictionary.

Example

在这个示例中,我们使用不同的默认工厂来初始化 defaultdict 的实例:int,可以使用 0 来初始化丢失的键,list,可以使用空列表来初始化丢失的键,以及自定义函数 default_value,可以使用该函数的返回值来初始化丢失的键:

In this example, we are initializing instances of defaultdict with different default factories: int to initialize missing keys with 0, list to initialize missing keys with an empty list, and a custom function default_value to initialize missing keys with the return value of the function −

from collections import defaultdict
# Using int as the default factory to initialize missing keys with 0
d = defaultdict(int)
# Incrementing the value for key 'a'
d["a"] += 1
print(d)

# Using list as the default factory to initialize missing keys with an empty list
d = defaultdict(list)
# Appending to the list for key 'b'
d["b"].append(1)
print(d)

# Using a custom function as the default factory
def default_value():
    return "N/A"

d = defaultdict(default_value)
print(d["c"])

获得的输出如下 −

The output obtained is as follows −

defaultdict(<class 'int'>, {'a': 1})
defaultdict(<class 'list'>, {'b': [1]})
N/A