1 回答
TA贡献1884条经验 获得超4个赞
您可以与递归一起使用:itertools.groupby
from itertools import groupby as gb
import re
def get_dict(d):
_r, _d = [], {}
for a, _b in gb(d, key=lambda x:not x[0]):
if a:
_r.extend([u for _, u in _b])
else:
_d[_r.pop()] = get_dict([[j[4:], k] for j, k in _b])
return _r+([] if not _d else [_d])
import json
data = [re.findall('^\s+|[\w\-]+', i) for i in filter(None, content.split('\n'))]
print(json.dumps(get_dict([['' if not a else a[0], b] for *a, b in data]), indent=4))
输出:
[
{
"part-a": [
"thing-a",
{
"part-a-a": [
"thing-a"
],
"part-a-b": [
"thing-a",
"thing-b"
]
}
],
"part-b": [
"thing-a",
"thing-b",
"thing-c"
]
}
]
添加回答
举报