How to turn a list into nested dict in Python(如何将列表转换为 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("/")
,如伪示例中的['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 中的嵌套字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!