在python中将路径列表转换为字典

2024-09-28 22:11:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用Python编写一个程序,在这个程序中,我需要与“假想的”路径(即在实际文件系统中不存在也不会存在的路径)进行交互,并且我需要能够listdir像正常情况一样返回它们(path['directory']会像os.listdir()一样返回目录中的每一项)。你知道吗

我提出的解决方案是将字符串路径列表转换为字典。我提出了这个递归函数(它在一个类中):

    def DoMagic(self,paths):
        structure = {}
        if not type(paths) == list:
            raise ValueError('Expected list Value, not '+str(type(paths)))
        for i in paths:
            print(i)
            if i[0] == '/': #Sanity check
                print('trailing?',i) #Inform user that there *might* be an issue with the input.
                i[0] = ''
            i = i.split('/') #Split it, so that we can test against different parts.
            if len(i[1:]) > 1: #Hang-a-bout, there's more content!
                structure = {**structure, **self.DoMagic(['/'.join(i[1:])])}
            else:
                structure[i[1]] = i[1]

但是当我以['foo/e.txt','foo/bar/a.txt','foo/bar/b.cfg','foo/bar/c/d.txt']作为输入运行它时,我得到:

{'e.txt': 'e.txt', 'a.txt': 'a.txt', 'b.cfg': 'b.cfg', 'd.txt': 'd.txt'}

我希望能够path['foo']['bar']获取foo/bar/目录中的所有内容。你知道吗

编辑:

更理想的产出是:

    {'foo':{'e.txt':'e.txt','bar':{'a.txt':'a.txt','c':{'d.txt':'d.txt'}}}}

Tags: pathself路径程序目录txtiffoo
2条回答

这个怎么样。它可以得到您想要的输出,但是树结构可能更干净。你知道吗

from collections import defaultdict
import json

def nested_dict():
   """
   Creates a default dictionary where each value is an other default dictionary.
   """
   return defaultdict(nested_dict)

def default_to_regular(d):
    """
    Converts defaultdicts of defaultdicts to dict of dicts.
    """
    if isinstance(d, defaultdict):
        d = {k: default_to_regular(v) for k, v in d.items()}
    return d

def get_path_dict(paths):
    new_path_dict = nested_dict()
    for path in paths:
        parts = path.split('/')
        if parts:
            marcher = new_path_dict
            for key in parts[:-1]:
               marcher = marcher[key]
            marcher[parts[-1]] = parts[-1]
    return default_to_regular(new_path_dict)

l1 = ['foo/e.txt','foo/bar/a.txt','foo/bar/b.cfg','foo/bar/c/d.txt', 'test.txt']
result = get_path_dict(l1)
print(json.dumps(result, indent=2))

输出:

{
  "foo": {
    "e.txt": "e.txt",
    "bar": {
      "a.txt": "a.txt",
      "b.cfg": "b.cfg",
      "c": {
        "d.txt": "d.txt"
      }
    }
  },
  "test.txt": "test.txt"
}

通过字典实现的简单树不就足够了吗? 你的实现似乎有点多余。很难说文件属于哪个文件夹。你知道吗

https://en.wikipedia.org/wiki/Tree_(data_structure)

如果你需要额外的东西,pypi上有很多lib。 treelib

pathlib中也有Pure paths。你知道吗

相关问题 更多 >