是否可以获取Python字典的所有嵌套字段名称?
例如:
字典:
{
"a": [
{
"b": {
"c": [
"f",
"g"
]
}
}
]
}
结果:
'a[0].b.c[0]'
'a[0].b.c[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]']