You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python 2.7中基于键值对合并两个字典列表的方法

嘿,这个需求我平时处理数据的时候经常碰到!结合你给出的data_list例子,我给你几个实用的解决方案,分场景来看:

基于单个共有键合并(比如你例子里的key)

这是最常见的场景,我们可以先把其中一个列表转成字典(用共有键作为索引),这样匹配效率会高很多,避免嵌套循环拖慢速度。

假设你另一个列表叫other_list,每个字典也包含key这个共有键,代码可以这么写:

# 先把other_list转成以'key'为键的字典,方便快速查找匹配项
other_lookup = {item['key']: item for item in other_list}

merged_result = []
for data_item in data_list:
    current_key = data_item['key']
    # 如果找到匹配的项,就合并两个字典
    if current_key in other_lookup:
        # 用**解包合并,后面的字典会覆盖前面重复的键(按需调整顺序)
        combined_item = {**data_item, **other_lookup[current_key]}
        merged_result.append(combined_item)
    else:
        # 没有匹配项的话,可选保留原数据或者跳过
        merged_result.append(data_item)

如果担心重复键的覆盖问题——比如想优先保留data_list里的键值,就把data_item放在后面:{**other_lookup[current_key], **data_item}。

基于多个共有键合并

如果需要多个键同时匹配才合并(比如app和end_time都相同才算匹配),可以把多个键组合成元组作为索引:

# 把other_list转成以(app, end_time)为复合键的字典
other_lookup = {(item['app'], item['end_time']): item for item in other_list}

merged_result = []
for data_item in data_list:
    # 生成复合匹配键
    match_key = (data_item['app'], data_item['end_time'])
    if match_key in other_lookup:
        combined_item = {**data_item, **other_lookup[match_key]}
        merged_result.append(combined_item)
    else:
        merged_result.append(data_item)

这样只有当两个字典的app和end_time完全一致时,才会执行合并操作。

双向保留所有匹配项

如果不仅要把other_list的内容合并到data_list,还要保留data_list里没有但other_list有的项,可以这么处理:

# 把两个列表都转成以'key'为键的字典
data_lookup = {item['key']: item for item in data_list}
other_lookup = {item['key']: item for item in other_list}

# 获取所有唯一的键
all_keys = set(data_lookup.keys()).union(other_lookup.keys())

merged_result = []
for key in all_keys:
    combined_item = {}
    # 合并两个字典的内容
    if key in data_lookup:
        combined_item.update(data_lookup[key])
    if key in other_lookup:
        combined_item.update(other_lookup[key])
    merged_result.append(combined_item)

这样不管是哪个列表里的项,只要有匹配的键都会被合并,没有匹配的也会完整保留各自的内容。

小提醒

  • 如果你的字典里可能存在缺失共有键的情况,记得加判断(比如if 'key' in data_item),避免抛出KeyError。
  • 如果你用的是Python 3.5之前的版本,**解包语法不支持,可以改用data_item.copy().update(other_lookup[current_key])来合并字典。

内容的提问来源于stack exchange,提问作者Prof. Falken

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:04:59