不使用Pandas将Python嵌套字典转换为二维列表/表格的方法
嵌套字典转二维列表的Pythonic实现方案
我们需要将指定嵌套字典转换为二维列表,后续基于该列表构建表格,不可使用Pandas库,求最符合Pythonic风格的实现方式。
输入示例
原始嵌套字典log
log={ 'hKtN': { 'edit_field': ['id','coord'], 'ids': { '4A': { 'update_type': 'delete' }, '1A': { 'update_type': '', 'update_detail': [] }, '2A': { 'update_type': 'edit', 'update_detail': ['0913','0914'] } } } }
简化版输入字典log2
如果使用结构更清晰的log2作为输入更易实现,也可以使用该版本:
log2={ 'logId': 'hKtN', 'edit_field': [ 'id', 'coord' ], 'ids': { '4A': { 'update_type': 'delete' }, '1A': { 'update_type': '', 'update_detail': [ ] }, '2A': { 'update_type': 'edit', 'update_detail': [ '0913', '0914' ] } } }
目标输出
二维列表格式
table = [ ['hKtN',['id','coord'],'4A','delete',''], ['hKtN',['id','coord'],'1A','',''], ['hKtN',['id','coord'],'2A','edit',['0913','0914']] ]
最终表格效果
logId | edit_field | ids | update_type | update_detail -------------------------------------------------------------- hKtN | ['id','coord'] | 4A | delete | hKtN | ['id','coord'] | 1A | | hKtN | ['id','coord'] | 2A | edit |['0913','0914']
实现代码
针对简化版log2的实现
通过嵌套列表推导式实现,逻辑简洁无冗余,兼容缺省字段:
table = [ [log2['logId'], log2['edit_field'], id_val, detail.get('update_type', ''), detail.get('update_detail', '')] for id_val, detail in log2['ids'].items() ]
这里用dict.get()处理缺省字段,不需要额外的分支判断,符合Pythonic编码习惯。
针对原始log的实现
如果需要直接处理原始嵌套结构的log,只需在外层加一层遍历即可:
table = [ [log_id, log_info['edit_field'], id_val, detail.get('update_type', ''), detail.get('update_detail', '')] for log_id, log_info in log.items() for id_val, detail in log_info['ids'].items() ]
代码全程无第三方库依赖,运行后输出的二维列表完全匹配要求格式,可直接用于后续表格构建。
内容的提问来源于stack exchange,提问作者franco_b
相关产品推荐
相关产品推荐

