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

如何基于公共键将Python字典列表合并为单个字典?

问题描述

我有如下字典列表:

data= [{'org_id': 'AGO-cbgo', 'ws_name': 'finops_enricher-nonprod', 'ws_id': 'ws-CTvV7QysPeY4Gt1Q', 'current_run': None},
{'org_id': 'AGO-cbgo', 'ws_name': 'finops_enricher-prod', 'ws_id': 'ws-s4inidN9aDxELE4a', 'current_run': None},
{'org_id': 'AGO-cbgo', 'ws_name': 'finops_enricher-preprod', 'ws_id': 'ws-fvyKv7m4FRYf8v5o', 'current_run': None},
{'org_id': 'AGO-cbgo', 'ws_name': 's3_dlp-getd_sherlock-prod', 'ws_id': 'ws-XpzzptzGHL2YNjsL', 'current_run': None},
{'org_id': 'AGO-cbgo', 'ws_name': 's3_dlp-getd_sherlock-nonprod', 'ws_id': 'ws-dksk8nnXTjzLWmRn', 'current_run': 'run-osSNuCtt5ULHPBus'}
]

需要得到如下结果:

result= {'AGO-cbgo': {'ws': [
            {'ws_name': 'finops_enricher-nonprod', 'ws_id': 'ws-CTvV7QysPeY4Gt1Q', 'current_run': None},
            {'ws_name': 'finops_enricher-preprod', 'ws_id': 'ws-fvyKv7m4FRYf8v5o', 'current_run': None},
            {'ws_name': 's3_dlp-getd_sherlock-prod', 'ws_id': 'ws-XpzzptzGHL2YNjsL', 'current_run': None},
            {'ws_name': 's3_dlp-getd_sherlock-nonprod', 'ws_id': 'ws-dksk8nnXTjzLWmRn', 'current_run': 'run-osSNuCtt5ULHPBus'}
            ]
        }}

我尝试过使用collections和defaultdict但未成功,请问该如何实现?

解决方案

核心逻辑是按org_id分组,剔除每个字典中的org_id字段后,将剩余内容归入对应分组的ws列表,以下两种方法都能实现:

方法一:普通字典实现

result = {}
for item in data:
    # 取出org_id并从原字典移除
    org_id = item.pop('org_id')
    # 若该org_id未在结果中,初始化结构
    if org_id not in result:
        result[org_id] = {'ws': []}
    # 将处理后的字典加入ws列表
    result[org_id]['ws'].append(item)

方法二:defaultdict实现

如果之前用defaultdict失败,大概率是嵌套结构初始化错误,正确写法如下:

from collections import defaultdict

# 初始化默认值为包含ws空列表的字典
result = defaultdict(lambda: {'ws': []})
for item in data:
    org_id = item.pop('org_id')
    result[org_id]['ws'].append(item)
# 若需要转为普通字典,执行:result = dict(result)

注意事项

如果不想修改原始data列表,不要用pop,改用字典推导式复制并过滤字段:

item_copy = {k: v for k, v in item.items() if k != 'org_id'}

再将item_copy添加到ws列表即可。


内容的提问来源于stack exchange,提问作者WorkoutBuddy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 14:10:25