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

Python字典列表扁平化实现时报AttributeError错误问题求解

问题根因
  • 函数入参逻辑设计错误:你当前写的flatten函数没有区分「要处理的是字典列表还是单个字典」,递归调用时传入的单字典会被外层for dictionary in datalist遍历键(字符串类型),后续调用.items()自然抛出属性不存在的错误。
  • 输出结果不符合预期:原函数会把输入列表里所有字典的键合并成一个字典返回,重复键会被覆盖,得不到你要的「每个原字典单独扁平化」的结果。
  • 额外兼容问题:Python 3.3+ 之后collections.MutableMapping已经迁移到collections.abc模块下,直接用旧导入方式会触发弃用警告。
修复方案

拆分逻辑:先实现专门处理单个字典递归扁平化的工具函数,再遍历输入的字典列表,对每个元素单独调用工具函数收集结果即可。

from collections.abc import MutableMapping

# 单个字典递归扁平化工具
def flatten_single_dict(d, parent_key=None, separator='-'):
    items = []
    parent_key = parent_key or ''
    for k, v in d.items():
        new_key = f"{parent_key}{separator}{k}" if parent_key else k
        if isinstance(v, MutableMapping):
            items.extend(flatten_single_dict(v, new_key, separator=separator).items())
        elif isinstance(v, list):
            for idx, val in enumerate(v):
                items.extend(flatten_single_dict({str(idx): val}, new_key, separator=separator).items())
        else:
            items.append((new_key, v))
    return dict(items)

# 处理字典列表的对外接口
def flatten_dict_list(datalist, separator='-'):
    return [flatten_single_dict(item, separator=separator) for item in datalist]
调用示例
x = [{'website_ctr': [{'action_type': 'link_click', 'value': '0.481928'}],
  'campaign_id': 'x',
  'date_start': '2021-11-01',
  'date_stop': '2021-11-01',
  'account_id': 'y'},
 {'website_ctr': [{'action_type': 'link_click', 'value': '0.40568'}],
  'campaign_id': 'x',
  'date_start': '2021-11-01',
  'date_stop': '2021-11-01',
  'account_id': 'y'},
 {'website_ctr': [{'action_type': 'link_click', 'value': '0.711382'}],
  'campaign_id': 'x',
  'date_start': '2021-11-01',
  'date_stop': '2021-11-01',
  'account_id': 'y'}]

result = flatten_dict_list(x)
print(result[0])
# 输出符合预期:{'website_ctr-0-action_type': 'link_click', 'website_ctr-0-value': '0.481928', 'campaign_id': 'x', 'date_start': '2021-11-01', 'date_stop': '2021-11-01', 'account_id': 'y'}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 02:15:05