如何将列表转换为Python中的嵌套字典 [英] How to turn a list into nested dict in Python
问题描述
需要转换x:
X = [['A', 'B', 'C'], ['A', 'B', 'D']]
进入Y:
Y = {'A': {'B': {'C','D'}}}
更具体地说,我需要从绝对路径列表中创建一个文件夹和文件树,如下所示:
More specifically, I need to create a tree of folders and files from a list of absolute paths, which looks like this:
paths = ['xyz/123/file.txt', 'abc/456/otherfile.txt']
其中,每个路径是 split(/)
code> ['A','B','C'] 在伪示例中。
where, each path is split("/")
, as per ['A', 'B', 'C']
in the pseudo example.
由于这表示文件和文件夹,显然,在同一级别(数组的索引)上,同名字符串不能重复。
As this represents files and folders, obviously, on the same level (index of the array) same name strings can't repeat.
推荐答案
X = [['A', 'B', 'C'], ['A', 'B', 'D'],['W','X'],['W','Y','Z']]
d = {}
for path in X:
current_level = d
for part in path:
if part not in current_level:
current_level[part] = {}
current_level = current_level[part]
这给我们带来了包含 {'A ':{'B':{'C':{},'D':{}}},'W':{'Y':{'Z':{}},'X':{}}}
。包含空字典的任何项目都是文件或空目录。
This leaves us with d containing {'A': {'B': {'C': {}, 'D': {}}}, 'W': {'Y': {'Z': {}}, 'X': {}}}
. Any item containing an empty dictionary is either a file or an empty directory.
这篇关于如何将列表转换为Python中的嵌套字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!