获取Python中字典的所有字段名称

时间:2019-10-09 11:54:16

标签: python dictionary

是否可以获取Python字典的所有嵌套字段名称?

例如:

字典:

{
   "a": [
      {
         "b": {
            "c": [
               "f",
               "g"
            ]
         }
      }
   ]
}

结果:

'a[0].b.c[0]'
'a[0].b.c[1]'

1 个答案:

答案 0 :(得分:2)

您可以将递归与生成器一起使用:

def traverse(d, c = []):
  if isinstance(d, list):
    for i, a in enumerate(d):
      if not isinstance(a, (dict, list)):
        yield '.'.join(c+[f'[{i}]'])
      else:
        yield from traverse(a, c+[f'[{i}]'])
  elif isinstance(d, dict):
     for a, b in d.items():
        if not isinstance(b, (list, dict)):
           yield '.'.join(c+[a])
        else:
           yield from traverse(b, c+[a])


d = {'a': [{'b': {'c': ['f', 'g']}}]}
import re
print([re.sub('\.(?=\[)', '', i) for i in traverse(d)])

输出:

['a[0].b.c[0]', 'a[0].b.c[1]']