如何提取嵌套字典指定键值生成目标格式pandas DataFrame
嵌套字典转目标DataFrame实现方案
核心注意点:原始数据里tags对应的value是JSON序列化后的字符串,需要先反序列化才能正常解析,再关联上articleId即可得到目标结果。
注意:你给出的预期输出里的englistname为拼写笔误,实际对应字段是englishName
前置依赖
需要导入pandas和json两个库。
完整实现代码
import pandas as pd import json # 原始嵌套字典 raw_dict = { "getArticleAttributesResponse": { "attributes": [{ "articleId": { "id": "2345", "locale": "en_US" }, "keyValuePairs": [{ "key": "tags", "value": "[{\"displayName\": \"Nice\", \"englishName\": \"Pradeep\", \"refKey\": \"Key2\"}, {\"displayName\": \"Family Sharing\", \"englishName\": \"Sarvendra\", \"refKey\": \"Key1\", \"meta\": {\"customerDisplayable\": [false]}}]" }] }] } } # 提取核心字段 attributes = raw_dict["getArticleAttributesResponse"]["attributes"][0] article_id = attributes["articleId"]["id"] # 提取key为tags的value字符串 tags_str = next(kv["value"] for kv in attributes["keyValuePairs"] if kv["key"] == "tags") # 反序列化JSON字符串为字典列表 tags_list = json.loads(tags_str) # 生成目标DataFrame df = pd.DataFrame(tags_list) df["id"] = article_id # 筛选需要的列 df = df[["id", "displayName", "englishName", "refKey"]] # 打印验证结果 print(df)
输出结果
id displayName englishName refKey 0 2345 Nice Pradeep Key2 1 2345 Family Sharing Sarvendra Key1
内容的提问来源于stack exchange,提问作者Sarvendra Singh
相关产品推荐
相关产品推荐

