跳至主要内容

Python 字典追加:如何添加键值对

学习如何使用方括号表示法、用于批量添加的 .update(),以及用于有条件插入的 .setdefault(),在 Python 字典中追加键值对。
· 8分钟 阅读

使用 AI 探索

在 Python 编程中,字典非常灵活,您可以用键值对来存储数据,以便高效管理与访问。如果您刚接触 Python,理解如何操作字典至关重要,因为这将极大提升您在各类应用中处理数据的能力。无论是配置设置、管理复杂数据集,还是仅用于快速查找,字典都是理想之选。

您经常需要进行的关键操作之一就是向字典中追加元素。本文将带您了解在 Python 中向字典追加条目的不同方法,从基础的方括号表示法到更高级的 update() 方法和合并运算符等技巧。

如果您对 Python 中的字典还不熟悉,建议同时阅读我们的 Python 字典教程,或 Python 字典推导式教程,它们是学习键值对和字典基础概念的优质资源。此外,如果您需要快速回顾 Python 语法与函数,我们的 Python 入门速查表也会很有用。

快速答案:如何在 Python 中向字典追加

如果您在寻找一种快速向 Python 字典追加元素的方法,update() 是最常见且易用的方式之一:

# Initial dictionary with information for one person
people_info = {
    'person_1': {
        'name': 'Alice',
        'city': 'New York'
    }
}

# Updating Alice's information and adding another person
people_info.update({
    'person_1': {
        'name': 'Alice',
        'city': 'Los Angeles',  # Updated city
        'age': 30               # Added new detail
    },
    'person_2': {
        'name': 'Bob',
        'city': 'San Francisco'
    }
})

print(people_info)

# {
#     'person_1': {'name': 'Alice', 'city': 'Los Angeles', 'age': 30},
#     'person_2': {'name': 'Bob', 'city': 'San Francisco'}
# }

在此示例中,update() 方法会更新键 'person_1' 下 Alice 的信息,将她的 city 改为 'Los Angeles',并新增 age: 30。它还会在键 'person_2' 下新增 Bob。

理解 Python 字典

首先,我们来讨论什么是 Python 字典,以及它为何在编程中如此重要。

什么是 Python 字典?

Python 中的字典是由键值对组成的集合。字典中的每个键都是唯一的,并映射到一个值,该值可以是任意数据类型(如字符串、整数、列表,甚至其他字典)。这种结构便于数据的检索、添加和修改。下面是一个简单示例:

# Example of a dictionary
person = {
    'name': 'Alice',
    'age': 25,
    'city': 'New York'
}

# Accessing a value
print(person['name'])  # Output: Alice

在这个示例中,'name'、'age' 和 'city' 是键,而 'Alice'、25 和 'New York' 则是相应的值。

Python 字典的结构

字典是无序集合,这意味着其条目没有固定顺序。然而,从 Python 3.7 开始,字典会保持插入顺序,这在许多场景中都很有用。下面用一个更详细的示例来说明其结构:

# A more complex dictionary
employee = {
    'id': 101,
    'name': 'John Doe',
    'age': 30,
    'department': 'Engineering',
    'skills': ['Python', 'Machine Learning', 'Data Analysis'],
    'address': {
        'street': '123 Main St',
        'city': 'San Francisco',
        'state': 'CA',
        'zip': '94105'
    }
}

# Accessing nested data
print(employee['skills'][1])  # Output: Machine Learning
print(employee['address']['city'])  # Output: San Francisco

在这个示例中,employee 字典包含多种类型的数据,包括列表('skills')和另一个字典('address')。这展示了字典如何用于存储和组织复杂的数据结构。

了解了基础之后,我们来更详细地探索向字典追加元素的多种方法。

在 Python 中向字典追加元素的方法

在 Python 中向字典追加元素是常见任务,有多种方法可用,各自适用于不同场景并各有优势。我们逐一来看。

使用方括号表示法

向字典添加单个键值对最直接的方法就是使用方括号表示法。该方法简单高效,适合添加单个元素。其语法如下:

dictionary[key] = value

下面是使用方括号表示法的示例:

# Initialize a dictionary
my_dict = {'name': 'Alice', 'age': 25}

# Add a new key-value pair
my_dict['city'] = 'New York'

# Print the updated dictionary
print(my_dict)
# Output: {'name': 'Alice', 'age': 25, 'city': 'New York'}

这种方式会直接在字典中添加或更新键值对。如果键已存在,其值会被更新。

当您用方括号表示法为已存在的键赋值时,该键对应的值将被更新。根据需求不同,这既可能是特性,也可能是注意点。下面演示如何处理已存在的键:

# Initialize a dictionary
my_dict = {'name': 'Alice', 'age': 25}

# Add a new key-value pair
my_dict['city'] = 'New York'

# Update an existing key-value pair
my_dict['age'] = 30

# Print the updated dictionary
print(my_dict)
# Output: {'name': 'Alice', 'age': 30, 'city': 'New York'}

在此示例中,键 'age' 的值从 25 更新为 30。

使用 .update() 方法

.update() 方法可以一次性向字典添加多个键值对。它可接收另一个字典或由键值对组成的可迭代对象。其语法如下:

dictionary.update(other)

下面是使用 .update() 方法的示例:

# Initialize a dictionary
my_dict = {'name': 'Alice', 'age': 25}

# Add new key-value pairs using update()
my_dict.update({'city': 'New York', 'email': '[email protected]'})

# Print the updated dictionary
print(my_dict)
# Output: {'name': 'Alice', 'age': 25, 'city': 'New York', 'email': '[email protected]'}

.update() 也可以与由键值对组成的可迭代对象一起使用。示例如下:

# Initialize a dictionary
my_dict = {'name': 'Alice', 'age': 25}

# Add new key-value pairs using update() with an iterable
my_dict.update([('city', 'New York'), ('email', '[email protected]')])

# Print the updated dictionary
print(my_dict)
# Output: {'name': 'Alice', 'age': 25, 'city': 'New York', 'email': '[email protected]'}

当您需要一次性添加多条新记录时,.update() 尤其有用。如果键已存在,其值会被更新。

使用 .setdefault() 方法

.setdefault() 方法仅在键不存在时,才向字典添加键值对;如果键已存在,则返回其现有值。其语法如下:

dictionary.setdefault(key, default_value)

下面是使用 .setdefault() 的示例:

# Initialize a dictionary
my_dict = {'name': 'Alice', 'age': 25}

# Use setdefault to add a new key-value pair
my_dict.setdefault('city', 'New York')

# Attempt to add an existing key
my_dict.setdefault('age', 30)

# Print the updated dictionary
print(my_dict)
# Output: {'name': 'Alice', 'age': 25, 'city': 'New York'}

在此示例中,.setdefault() 会添加键 'city',值为 'New York',因为该键此前不存在。当尝试添加键 'age' 时,由于已存在,因此不会将其值从 25 改为 30。

当您需要确保某个键在不存在时具有默认值,这种方法很合适。它也适用于在不覆盖已有键的情况下添加新键值对。

使用 dict() 构造函数

您也可以通过 dict() 构造函数创建一个包含额外键值对的新字典。这在您希望基于现有字典创建新字典时很有用。其语法如下:

new_dict = dict(existing_dict, key1=value1, key2=value2)

下面是使用 dict() 构造函数的示例:

# Initialize a dictionary
my_dict = {'name': 'Alice', 'age': 25}

# Create a new dictionary with additional key-value pairs
new_dict = dict(my_dict, city='New York', email='[email protected]')

# Print the new dictionary
print(new_dict)
# Output: {'name': 'Alice', 'age': 25, 'city': 'New York', 'email': '[email protected]'}

在此示例中,使用 dict() 构造函数创建了新字典 new_dict,它包含 my_dict 中的原始键值对,以及新增的 'city': 'New York' 与 'email': '[email protected]'。

当您希望在保留原字典不变的前提下,合并现有字典与额外键值对来创建新字典时,这种方法很合适;也可在需要基于原字典做一些修改并生成新字典时使用。

对比表

以下是我们在教程中涵盖方法的快速参考表:

方法适用场景示例
方括号单个键值对dict[key] = value
.update()多个键值对dict.update({key1: value1, key2: value2})
.setdefault()仅在键不存在时添加键值对dict.setdefault(key, default_value)
dict() 构造函数创建新字典,或在现有基础上加入额外键值对new_dict = dict(existing_dict, key1=value1, key2=value2)

在 Python 中向字典追加的高级技巧

掌握字典操作的基础很重要,但要真正精通 Python 字典,还需探索一些高级技巧。这些方法能帮助您在更复杂的场景中高效管理与操作字典。

向字典中的列表追加

字典常常用于将列表作为值进行存储。向这些列表追加元素需要稍有不同的做法。您可以使用 .append() 来实现:

# Initialize a dictionary with a list as a value
dictionary_w_list = {'fruits': ['apple', 'banana']}

# Append an element to the list within the dictionary
dictionary_w_list['fruits'].append('cherry')

# Print the updated dictionary
print(dictionary_w_list)
# Output: {'fruits': ['apple', 'banana', 'cherry']}

在该示例中,我们从 dictionary_w_list 出发,其中键 'fruits' 映射到列表 ['apple', 'banana']。通过使用 .append() 方法,我们将 'cherry' 添加到该列表中。这在用一个字典管理一组集合时尤其有用。

使用合并运算符合并字典

Python 3.9 引入了合并运算符(|),用于合并字典。它可以轻松将两个字典合并为一个新字典:

# Initialize two dictionaries
first_dictionary = {'name': 'Alice', 'age': 25}
second_dictionary = {'city': 'New York', 'email': '[email protected]'}

# Merge the dictionaries using the merge operator
merged_dictionary = first_dictionary | second_dictionary

# Print the merged dictionary
print(merged_dictionary)
# Output: {'name': 'Alice', 'age': 25, 'city': 'New York', 'email': '[email protected]'}

在此示例中,first_dictionary 和 second_dictionary 被合并为新字典 merged_dictionary。合并运算符(|)将两个字典中的键值对组合起来,是一种快速便捷的合并方式。

使用更新运算符

对于就地更新,Python 3.9 还引入了更新运算符 |=。该运算符可将另一个字典的键值对更新到原字典中。

# Initialize two dictionaries
first_dictionary = {'name': 'Alice', 'age': 25}
second_dictionary = {'city': 'New York', 'email': '[email protected]'}

# Update dict1 in-place using the update |= operator
first_dictionary |= second_dictionary

# Print the updated dictionary
print(first_dictionary)
# Output: {'name': 'Alice', 'age': 25, 'city': 'New York', 'email': '[email protected]'}

这里,更新运算符 |= 将 second_dictionary 的内容原地更新到 first_dictionary 上,即直接修改原字典。当您需要在不创建新字典的情况下更新现有字典时,这种方式尤其实用。

结语

本文学习了 Python 字典以及追加键值对的方法。我们从基础技巧开始,如方括号表示法和 .update() 方法,它们对于快速、直接的更新至关重要。随后,我们介绍了更高级的技巧,包括向字典中的列表追加、使用合并运算符(|)合并字典,以及用更新运算符 |= 进行就地更新。这些方法为管理复杂数据结构与高效操作提供了有力工具。

我们还有一些资源可帮助您进一步提升 Python 技能。您可以查看 Python 入门 课程,它是绝佳的起点,侧重数据科学应用并夯实 Python 基础。Python 编程技能路径也提供了系统全面的课程体系,助您从入门走向熟练。

我们的 Python 开发者 职业路径同样适合希望深入学习 Python 编程的读者,涵盖更复杂的编程结构与技巧。

Samuel Shaibu

作者

Samuel Shaibu

资深数据从业者与写作者,热衷于帮助有志于数据领域的专业人士成长与精进。

常见问题解答

如何向 Python 字典添加新的键值对?

您可以使用方括号表示法向 Python 字典添加新的键值对,例如 dictionary[key] = value。这种方法会就地更新字典。

Python 字典中的 .update() 方法是什么,如何使用?

.update() 方法用于向字典添加多个键值对。它可以接收另一个字典或由键值对组成的可迭代对象,并更新现有字典。

在 Python 中,.update() 方法与合并运算符 (|) 合并字典有何区别?

.update() 方法会就地修改现有字典,将另一个字典中的键值对添加进来,并可能覆盖已存在的键。合并运算符会创建一个新字典,包含两个字典的元素,而不改变原始字典。

主题