如何解析嵌套字典并提取指定字段生成目标格式数据
数据转换解决方案
问题说明
源数据:
ads_data = [{ "account_id": "12345", "display": [ { "action_type": "video_view", "value": "123", "content": [{"type" : "Adult", "subject" : " Geography "}] } ], "display 1": [ { "action_type": "video_view", "value": "321" } ] }]
期望输出竖线分隔的结构化格式:
account_id|display|display_content_type|display_content_subject|display1 12345|123|Adult|Geography|321
你尝试的代码未能正确提取嵌套字段、匹配表头与对应值,无法得到目标格式。
问题分析
你的现有代码存在几个关键问题:
- 未解析嵌套的
content字典,无法提取type和subject字段 - 未对键名做转换(比如原数据里的
"display 1"需要对应表头的display1) - 没有按行的逻辑组织数据,只是将所有值零散存入列表,无法对应到正确的列位置
实现代码
以下是可以实现需求的代码:
# 定义目标表头 headers = ["account_id", "display", "display_content_type", "display_content_subject", "display1"] # 存储结果的列表,先加入表头 result = ["|".join(headers)] for item in ads_data: # 提取account_id字段 account_id = item["account_id"] # 解析display字段的嵌套数据 display_data = item["display"][0] display_value = display_data["value"] content_info = display_data["content"][0] content_type = content_info["type"].strip() content_subject = content_info["subject"].strip() # 解析display 1字段的数值 display1_value = item["display 1"][0]["value"] # 组装成一行数据并转为竖线分隔格式 row = "|".join([account_id, display_value, content_type, content_subject, display1_value]) result.append(row) # 输出结果 for line in result: print(line)
运行这段代码后,即可得到你期望的结构化输出。
内容的提问来源于stack exchange,提问作者rd567
相关产品推荐
相关产品推荐

