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

如何在Python中将特定嵌套字典结构转换为单行列对应格式的DataFrame

如何将嵌套字典数据整理为指定格式的单行DataFrame?

我来帮你搞定这个需求!你需要把嵌套字典里的组织按对应的布尔属性分组,最终生成一行的DataFrame,用pandas配合简单的遍历就能轻松实现,具体步骤如下:

实现思路

  1. 先初始化一个字典,用来存储每列要收集的组织名称列表
  2. 遍历每个组织条目,提取组织的名称(也就是description字段)
  3. 检查每个布尔字段(origin、notifying、distribution、forAttention)是否为True,如果是就把当前组织名称加到对应列的列表里
  4. 把每个列表转成逗号分隔的字符串,最后用这个字典生成单行的DataFrame

完整代码示例

import pandas as pd

# 你的原始数据
data = [
    {'organization': {'id': 14, 'description': 'France'}, 'distribution': True, 'forAttention': True},
    {'organization': {'id': 38, 'description': 'Netherlands'}, 'distribution': True, 'forAttention': True},
    {'organization': {'id': 31, 'description': 'Poland'}, 'notifying': True, 'origin': True},
    {'organization': {'id': 17, 'description': 'United Kingdom'}, 'distribution': True}
]

# 初始化结果字典,对应DataFrame的列
result = {
    'Origin_ct': [],
    'Notifying_ct': [],
    'Distribution_ct': [],
    'ForAttention_ct': []
}

# 遍历每个组织条目
for item in data:
    org_name = item['organization']['description']
    # 检查各个布尔字段,符合条件就添加名称到对应列表
    if item.get('origin'):
        result['Origin_ct'].append(org_name)
    if item.get('notifying'):
        result['Notifying_ct'].append(org_name)
    if item.get('distribution'):
        result['Distribution_ct'].append(org_name)
    if item.get('forAttention'):
        result['ForAttention_ct'].append(org_name)

# 将每个列表转为逗号分隔的字符串(空列表则转为空字符串)
for key in result:
    result[key] = ', '.join(result[key])

# 生成单行DataFrame
df = pd.DataFrame([result])
print(df)

运行结果

运行后你会得到和示例完全一致的DataFrame:

Origin_ct Notifying_ct          Distribution_ct      ForAttention_ct
0    Poland        Poland  France, Netherlands, United Kingdom  France, Netherlands

补充说明

  • 用item.get('字段名')而不是直接取item['字段名'],是为了避免有些组织没有某个布尔字段时抛出KeyError,让代码更健壮
  • 如果某个字段没有任何组织满足条件,对应的列会显示为空字符串,你可以根据需求改成None或者其他默认值

内容的提问来源于stack exchange,提问作者Dawn.Sahil

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 04:42:31