Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将具有绝对文件路径的dict转换为嵌套dict这样的文件夹结构?_Python_Dictionary_Nested_Filepath - Fatal编程技术网

Python 如何将具有绝对文件路径的dict转换为嵌套dict这样的文件夹结构?

Python 如何将具有绝对文件路径的dict转换为嵌套dict这样的文件夹结构?,python,dictionary,nested,filepath,Python,Dictionary,Nested,Filepath,我的口述是: source\u dict={ “/a”:{“foo”:“bar”,“randomstuff”:3}, “/b/a”:{“some”:“thing”,“abc”:{“bx”:1}, “/b/g/h/g”:{“任何”:“值”} } 路径可以是无限深的,并且永远不会以/(>存储的“文件夹”不是空的)结束 几个小时以来,我一直试图将source\u dict转换成嵌套的dict,如: final_dict={”/:{ “a”:{“foo”:“bar”,“randomstuff”:3},

我的口述是:

source\u dict={
“/a”:{“foo”:“bar”,“randomstuff”:3},
“/b/a”:{“some”:“thing”,“abc”:{“bx”:1},
“/b/g/h/g”:{“任何”:“值”}
}
路径可以是无限深的,并且永远不会以
/
(>存储的“文件夹”不是空的)结束

几个小时以来,我一直试图将
source\u dict
转换成嵌套的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'}}}}}}

您的dicts不是有效的python,可能应该删除
{“bx”:1}
周围的括号?因为您已经编写了一些代码,请用您尝试过的代码更新问题。@Dan哦,我修复了dicts,谢谢