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"
]
}
]
添加回答
舉報