Python字典合并案例如何拼接字典

wen python案例 25

本文目录导读:

Python字典合并案例如何拼接字典

  1. 使用 update() 方法(最常用)
  2. 使用 解包操作符(Python 3.5+)
  3. 使用 运算符(Python 3.9+)
  4. 处理重复键的实用案例
  5. 实际应用场景

我来为你介绍几种Python字典合并的方法,从基础到进阶:

使用 update() 方法(最常用)

# 基础用法
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
# 方法1:直接修改原字典
dict1.update(dict2)
print(dict1)  # {'a': 1, 'b': 2, 'c': 3, 'd': 4}
# 方法2:创建新字典
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
new_dict = {}
new_dict.update(dict1)
new_dict.update(dict2)
print(new_dict)  # {'a': 1, 'b': 2, 'c': 3, 'd': 4}

使用 解包操作符(Python 3.5+)

dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
# 合并多个字典
merged = {**dict1, **dict2}
print(merged)  # {'a': 1, 'b': 2, 'c': 3, 'd': 4}
# 合并多个字典并添加新键值
merged = {**dict1, **dict2, 'e': 5}
print(merged)  # {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
# 处理重复键(后者的值会覆盖前者)
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged = {**dict1, **dict2}
print(merged)  # {'a': 1, 'b': 3, 'c': 4}

使用 运算符(Python 3.9+)

dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
# 合并创建新字典
merged = dict1 | dict2
print(merged)  # {'a': 1, 'b': 2, 'c': 3, 'd': 4}
# 原地更新
dict1 |= dict2
print(dict1)  # {'a': 1, 'b': 2, 'c': 3, 'd': 4}

处理重复键的实用案例

案例1:保留最大值

def merge_with_max(*dicts):
    """合并多个字典,相同的键保留最大值"""
    result = {}
    for d in dicts:
        for key, value in d.items():
            if key not in result or value > result[key]:
                result[key] = value
    return result
dict1 = {'a': 1, 'b': 3, 'c': 2}
dict2 = {'a': 5, 'b': 1, 'd': 4}
merged = merge_with_max(dict1, dict2)
print(merged)  # {'a': 5, 'b': 3, 'c': 2, 'd': 4}

案例2:合并值为列表的字典

def merge_dict_lists(*dicts):
    """合并多个字典,相同的键的值合并为列表"""
    result = {}
    for d in dicts:
        for key, value in d.items():
            if key not in result:
                result[key] = []
            if isinstance(value, list):
                result[key].extend(value)
            else:
                result[key].append(value)
    return result
dict1 = {'a': [1, 2], 'b': [3]}
dict2 = {'a': [4], 'b': [5, 6], 'c': [7]}
merged = merge_dict_lists(dict1, dict2)
print(merged)  # {'a': [1, 2, 4], 'b': [3, 5, 6], 'c': [7]}

案例3:嵌套字典深度合并

from collections.abc import Mapping
def deep_merge(dict1, dict2):
    """深度合并嵌套字典"""
    result = dict1.copy()
    for key, value in dict2.items():
        if key in result and isinstance(result[key], Mapping) and isinstance(value, Mapping):
            result[key] = deep_merge(result[key], value)
        else:
            result[key] = value
    return result
dict1 = {'a': 1, 'b': {'x': 10, 'y': 20}}
dict2 = {'b': {'y': 30, 'z': 40}, 'c': 3}
merged = deep_merge(dict1, dict2)
print(merged)  # {'a': 1, 'b': {'x': 10, 'y': 30, 'z': 40}, 'c': 3}

实际应用场景

配置文件合并

default_config = {
    'host': 'localhost',
    'port': 8080,
    'debug': False,
    'database': {
        'name': 'app_db',
        'user': 'root'
    }
}
user_config = {
    'port': 9000,
    'debug': True,
    'database': {
        'password': 'secret123'
    }
}
# 合并配置(用户配置优先)
final_config = deep_merge(default_config, user_config)
print(final_config)
# {'host': 'localhost', 'port': 9000, 'debug': True, 
#  'database': {'name': 'app_db', 'user': 'root', 'password': 'secret123'}}

聚合多源数据

sales_q1 = {'product_A': 100, 'product_B': 200}
sales_q2 = {'product_B': 150, 'product_C': 300}
# 合并并累加销售额
def merge_sales(*dicts):
    result = {}
    for d in dicts:
        for key, value in d.items():
            result[key] = result.get(key, 0) + value
    return result
total_sales = merge_sales(sales_q1, sales_q2)
print(total_sales)  # {'product_A': 100, 'product_B': 350, 'product_C': 300}
方法 Python版本 是否原地修改 性能
update() 4+ 中等
解包 5+ 较快
运算符 9+ 取决于用法 较快
自定义函数 任意 灵活 视实现而定

推荐:

  • Python 3.5+:使用 解包(简洁且性能好)
  • Python 3.9+:使用 运算符(语义清晰)
  • 需要复杂逻辑:自定义合并函数

抱歉,评论功能暂时关闭!