如何将具有绝对文件路径的字典转换为类似文件夹结构的嵌套字典?



我有一个这样的字典:

source_dict = {
"/a": {"foo": "bar", "randomstuff": 3},
"/b/a": {"some": "thing", "abc": {"bx": 1}},
"/b/g/h/g": {"any": "value"}
}

路径可能是无限深的,它们永远不会以/结束(>存储的不是空的"文件夹")

几个小时以来,我试图source_dict嵌套词典,例如:

final_dict = {"/": {
"a": {"foo": "bar", "randomstuff": 3},
"b": {"a": {"some": "thing", "abc": {"bx": 1}}, "g": {"h": {"g": {"any": "value"}}}}
}}

值不会更改。 有什么想法吗?

您可以将itertools.groupby与递归一起使用:

from itertools import groupby as gb
def group(d):
new_d = [(a, list(b)) for a, b in gb(sorted(d, key=lambda x:x[0][0]), key=lambda x:x[0][0])]
return {a:b[-1][-1] if not b[0][0][1:] else group([(c, k) for [_, *c], k in b]) for a, b in new_d}
source_dict = {"/a": {"foo": "bar", "randomstuff": 3}, "/b/a": {"some":"thing", "else":{"bx": 1}}, "/b/g/h/g": {"any": "value"}}
r = {'/':group([(list(filter(None, a.split('/'))), b) for a, b in source_dict.items()])}

输出:

{'/': {'a': {'foo': 'bar', 'randomstuff': 3}, 'b': {'a': {'some': 'thing', 'else': {'bx': 1}}, 'g': {'h': {'g': {'any': 'value'}}}}}}

最新更新