将Python嵌套字典转换为表或列表列表(不带Pandas)

2024-09-30 01:22:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要转换嵌套字典,如:

log={
     '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']

我不能用熊猫。做这件事最像Python的方式是什么

编辑 @Ajax1234的代码运行良好,但非常复杂,需要使用Pandas来构建表。如果可以帮助我构建一个更简单的日志字典,如:

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'
        ]
    }
}

}


Tags: logididsfield列表字典typetable
2条回答

首先,我想说:

import pandas as pd

df = pd.json_normalize(log)

这更简单,可以完成这项工作

可以使用递归生成器函数:

import itertools as it
log = {'hKtN': {'edit_field': ['id', 'coord'], 'ids': {'4A': {'update_type': 'delete'}, '1A': {'update_type': '', 'update_detail': []}, '2A': {'update_type': 'edit', 'update_detail': ['0913', '0914']}}}}
def flatten(d, c = [], k = 'logId'):
   a, b, m = [*c], [], []
   for x, y in d.items():
      if k in ['logId', 'ids']:
          m.append((k, x))
      if not isinstance(y, dict):
         a.append((x, y))
      else:
         b.append((x, y))
   if not b:
      yield from ([a] if not m else [[*a, j] for j in m])
   else:
      yield from [i for (x, y), j in it.zip_longest(b, m) 
          for i in flatten(y, c = a if j is None else [*a, j], k = x)]

tbl = [dict(i) for i in flatten(log)]
print(tbl)

输出:

[{'logId': 'hKtN', 'edit_field': ['id', 'coord'], 'ids': '4A', 'update_type': 'delete'}, {'logId': 'hKtN', 'edit_field': ['id', 'coord'], 'ids': '1A', 'update_type': '', 'update_detail': []}, {'logId': 'hKtN', 'edit_field': ['id', 'coord'], 'ids': '2A', 'update_type': 'edit', 'update_detail': ['0913', '0914']}]

相关问题 更多 >

    热门问题