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 中的嵌套字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将列表转换为 Python 中的嵌套字典
基础教程推荐
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 求两个直方图的卷积 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 包装空间模型 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
