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 中的嵌套字典


- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01