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 中的嵌套字典
基础教程推荐
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
