三种常用方法合并 Python 字典,你学会了吗?

2025-04-21ASPCMS社区 - fjmyhfvclm

在使用 Python字典时,你有时需要将多个字典合并成一个,以便后续处理。

本教程将介绍三种常见的 Python 字典合并方法。我们将重点学习以下三种方式:

  • 使用 update 方法
  • 字典解包
  • 并集运算符(|)

让我们开始吧!

注意:你可以在 GitHub上找到相关代码示例。

  1. 使用 update 方法

要合并两个字典,可以使用字典的 update 方法。这个方法会用另一个字典的键值对更新现有字典,示例如下:

dict1.update(dict2)

这里:

  • dict1:需要被更新的原始字典。
  • dict2:其键值对将被添加到 dict1 中。

注意:此方法会直接修改原始字典。如果你不想修改原始字典,可以先创建一个副本再进行更新。

假设我们有两个包含数据库连接配置信息的字典 config1 和 config2:

config1 = { 'database': 'Postgres', 'host': 'localhost', 'port': 5432}config2 = { 'username': 'admin', 'password': 'secret', 'timeout': 30}

现在我们将 config1 的副本与 config2 合并:

# 使用 update 方法合并final_config = config1.copy# 创建副本,避免修改原始 config1final_config.update(config2)print(final_config)

如上所示,update 方法将 config2 的所有键值对添加到 final_config 中,最终得到包含所有配置信息的合并字典。

输出结果 >>>

展开全文

{ 'database': 'Postgres', 'host': 'localhost', 'port': 5432, 'username': 'admin', 'password': 'secret', 'timeout': 30}

2. 使用字典解包:{**dict1, **dict2}

就像可以解包元组一样,也可以使用 ** 运算符解包字典。这样可以通过解包两个字典的键值对来创建一个新字典。

假设有 dict1 和 dict2 两个字典,可以这样合并:

merged_dict = {**dict1, **dict2}

合并 config 字典的示例:

config1 = { 'database': 'Postgres', 'host': 'localhost', 'port': 5432}config2 = { 'username': 'admin', 'password': 'secret', 'timeout': 30}# 使用字典解包合并final_config = {**config1, **config2}print(final_config)

字典解包方法 {**config1, **config2} 创建了一个新的 final_config 字典,其中包含了 config1 和 config2 的所有键值对。

输出结果 >>>

{ 'database': 'Postgres', 'host': 'localhost', 'port': 5432, 'username': 'admin', 'password': 'secret', 'timeout': 30}

3. 使用并集 | 运算符

并集运算符(|)是在 Python 3.9 新增的一种合并字典的简洁方式。

你可以这样使用:

merged_dict = dict1 | dict2

这会将 dict1 和 dict2 合并成一个新字典。

config1 = { 'database': 'Postgres', 'host': 'localhost', 'port': 5432}config2 = { 'username': 'admin', 'password': 'secret', 'timeout': 30}# 使用 | 运算符合并final_config = config1 | config2print(final_config)

| 运算符将 config1 和 config2 合并为新的 final_config 字典:

输出结果 >>>

{ 'database': 'Postgres', 'host': 'localhost', 'port': 5432, 'username': 'admin', 'password': 'secret', 'timeout': 30}

总结

让我们回顾一下合并 Python 字典的几种不同方法:

  • update 方法(dict1.update(dict2))会更新已有字典。
  • {**dict1, **dict2} 使用解包方式创建一个新的合并字典。
  • 并集运算符|(Python 3.9+)可以用简单语法 dict1 | dict2 合并字典。

这并不是合并字典的全部方法。还有其他方式,比如列表推导式、使用 collections.ChainMap 创建合并视图等。但上述方法是最常用的几种。

祝你编程愉快!

全部评论