如何在Python中将列表转换为嵌套字典
需要将 x:
X = [['A', 'B', 'C'], ['A', 'B', 'D']]
转换为 Y:
Y = {'A': {'B': {'C','D'}}}
更具体地说,我需要从绝对路径列表创建文件夹和文件树,如下所示:
paths = ['xyz/123/file.txt', 'abc/456/otherfile.txt']
其中,每个路径都是 split("/")
,如伪示例中的 ['A', 'B', 'C']
所示。
由于这代表文件和文件夹,显然,在同一级别(数组的索引)上,同名字符串不能重复。
Need to turn x:
X = [['A', 'B', 'C'], ['A', 'B', 'D']]
Into 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']
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这使得 d 包含
{'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.假设
{'C', 'D'}
表示set(['C', 'D'])
并且您的 Python 版本支持字典理解 和
设置理解
,这是一个丑陋但有效的解决方案:至于您的示例:
但请不要在现实世界的应用程序中使用它:)
更新: 这里是一个可以任意使用的深度:
Assuming that
{'C', 'D'}
meansset(['C', 'D'])
and your Python version supportsdict comprehension
andset comprehension
, here's an ugly but working solution:As for your example:
But please don't use it in a real-world application :)
UPDATE: here's one that works with arbitrary depths:
您的问题陈述存在逻辑不一致。如果你真的想要
['xyz/123/file.txt', 'abc/456/otherfile.txt']
更改为
{'xyz': {'123': 'file.txt}, 'abc': {'456': 'otherfile.txt'}}
然后你必须回答路径 'abc.txt' 是如何实现的。没有前导文件夹的“txt”将被插入到此数据结构中。顶级字典键会是空字符串
''
吗?There is a logical inconsistency in your problem statement. If you really want
['xyz/123/file.txt', 'abc/456/otherfile.txt']
to be changed to
{'xyz': {'123': 'file.txt}, 'abc': {'456': 'otherfile.txt'}}
Then you have to answer how a path 'abc.txt' with no leading folder would be inserted into this data structure. Would the top-level dictionary key be the empty string
''
?这应该非常接近您所需要的:
结果:
This should be pretty close to what you need:
Results in:
我在 Twitter 上被问到这个问题,并使用函数式编程想出了这个巧妙的解决方案,我想我也可以在这里分享。
返回:
根据需要。
对于更简单的问题,您有一个列表想要表示为带有嵌套键的字典,这就足够了:
它返回:
I got asked about this question on twitter and came up with this slick solution using functional programming which I figure I might as well share here.
which returns:
as desired.
For the simpler problem where you have one list that you want to represent as a dict with nested keys, this will suffice:
which returns:
首先将键与值分开
现在使用它们来填充
NestedDict
要安装 ndicts
pip 安装 ndicts
First split keys from values
Now use them to populate a
NestedDict
To install ndicts
pip install ndicts