Python如何将嵌套字典的多层key拼接为点分隔的扁平化key
实现方案
通过递归处理单个嵌套字典的扁平化逻辑,递归过程中维护当前的父级key前缀,遇到值为字典类型就继续递归拼接key,遇到非字典类型就把拼接好的key和对应值存入结果字典,该方案可以自动适配任意深度的嵌套层级,不会出现深层key漏处理的问题。
核心实现代码
def flatten_dict(nested_dict, parent_key='', sep='.'): items = [] for k, v in nested_dict.items(): # 拼接当前层级的key new_key = f"{parent_key}{sep}{k}" if parent_key else k if isinstance(v, dict): # 子元素为字典,递归处理更深层级 items.extend(flatten_dict(v, new_key, sep=sep).items()) else: # 子元素非字典,直接存入结果 items.append((new_key, v)) return dict(items) # 处理字典数组的入口函数 def flatten_dict_array(nested_array): return [flatten_dict(item) for item in nested_array]
测试示例
输入示例
test_array = [ { "id": 1, "info": { "name": "test1", "contact": { "phone": "13xxxxxxxxx", "email": "test1@example.com" } }, "code": 200 }, { "id": 2, "info": { "name": "test2", "contact": { "phone": "13yyyyyyyyy", "email": "test2@example.com" } }, "code": { "status": 400, "msg": "error" } } ]
输出结果
[ { "id": 1, "info.name": "test1", "info.contact.phone": "13xxxxxxxxx", "info.contact.email": "test1@example.com", "code": 200 }, { "id": 2, "info.name": "test2", "info.contact.phone": "13yyyyyyyyy", "info.contact.email": "test2@example.com", "code.status": 400, "code.msg": "error" } ]
如果你的数据中还包含列表类型需要扁平化,只需要在flatten_dict函数中补充isinstance(v, list)的分支逻辑,按照需求拼接索引到key中即可。
内容的提问来源于stack exchange,提问作者Le Roy Loïc
相关产品推荐
相关产品推荐

