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

标签 python dictionary recursion filepath

我正在用 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'}}}}

最佳答案

Edit 10-14-22 我的第一个答案与 OP 的要求相符,但并不是真正理想的方法,也不是最干净的输出。由于这个问题似乎被更频繁地使用,请参阅下面的更简洁的方法,它对 Unix/Windows 路径更有弹性,并且输出字典更有意义。

from pathlib import Path
import json

def get_path_dict(paths: list[str | Path]) -> dict:
    """Builds a tree like structure out of a list of paths"""
    def _recurse(dic: dict, chain: tuple[str, ...] | list[str]):
        if len(chain) == 0:
            return
        if len(chain) == 1:
            dic[chain[0]] = None
            return
        key, *new_chain = chain
        if key not in dic:
            dic[key] = {}
        _recurse(dic[key], new_chain)
        return

    new_path_dict = {}
    for path in paths:
        _recurse(new_path_dict, Path(path).parts)
    return new_path_dict

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

输出:

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

旧方法

这个怎么样。它会获得您想要的输出,但是树结构可能更清晰。

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"
}

关于python - 将路径列表转换为python中的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58916584/

相关文章:

java - 对象不同,但通过 .equals 函数和 '==' 运算符获得

python - 如何从包含字母数字字符的单个列表创建元组?

python - 如何按键对字典进行排序?

python - 如何在不使用 Ordereddict 的情况下按键对 Python 字典进行排序?

java - 将递归方法变成迭代方法

php - 使用 shell_exec() 在 php 脚本中执行 python

python - 如何使用反斜杠 x\x 代码解码 ascii 字符串

Python配置库

python - 主窗口中的 Qt 对话框,使背景变暗

c# - 正则表达式递归替换