慕村9548890
您可以与递归一起使用:itertools.groupbyfrom itertools import groupby as gbimport redef 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 jsondata = [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" ] } ]