从可变长度的键列表中检查或设置嵌套dict中的项

2024-06-17 11:22:02 发布

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

我有一个嵌套的dict,它对应于如下目录树:

a:
  b:
    c: 1
    d: 1
  e:
    f:
      g: 1
      h: 1
...

在这种情况下,将数字作为值(c、d、g、h)的所有键都是文件,所有其他条目都是文件夹。现在给定一个类似于“a/e/f/g”的路径,我想执行以下操作:

  • 检查我的字典[a]是否存在,否则创建它
  • 检查我的字典[a][e]是否存在,否则创建它
  • 检查我的字典[a][e][f]是否存在,否则创建它
  • 检查my_dict[a][e][f][g]是否存在,否则创建它并为其指定默认值

不同文件的路径长度不是恒定的,因此我无法执行简单的chained.get()。此外,我还必须一个文件一个文件地添加条目

我想我的想法太复杂了。有什么优雅的方法吗

编辑: 例如:

我有上面的嵌套dict和一个路径为“a/b/I/j”且默认值为1的文件。然后,dict应按如下方式更新:

a:
  b:
    c: 1
    d: 1
    i:
      j: 1
  e:
    f:
      g: 1
      h: 1
...

Tags: 文件方法路径目录文件夹编辑get字典
2条回答
my_dict = {}
path = "a/e/f/g"
wd = my_dict  # Set working dictionary to my_dict
path_split = path.split('/')
for char in path_split[:-1]:  # Loop through all but the final char in the path
    if char not in wd or not isinstance(wd[char], dict):
        wd[char] = {}
    wd = wd[char]  # Set new working dictionary
if path_split[-1] not in wd:  # Check if final char is in the wd, if not set it to 1
    wd[path_split[-1]] = 1

您需要检查工作字典中是否存在键,以及相应的值是否为字典,然后在每次检查后设置工作字典

我拿了这样的dict,你应该根据你的要求来更改。我使用了一个path = 'Folder1/Folder12_/Folder121/File1211',其中Folder12_不在superdirectory中

df = {
    'Folder1': {
        'Folder11': {
            'File111': 1,
            'File112': 1,
        },
        'Folder12': {
            'Folder121': {
                'File1211': 1,
                'File1212': 1,
            }
        }
    }
}

path = 'Folder1/Folder12_/Folder121/File1211'.split('/')

df_test = df
ind_last = 0
for i in path:
    ind_last = path.index(i)
    if df_test.get(i):
        df_test = df_test.get(i)
    else:
        break

for i in path[ind_last:]:
    if path.index(i) != 3:
        df_test[i] = {}
        df_test = df_test.get(i)
    else:
        df_test[i] = 1
        df_test = df_test.get(i)
print(df)

相关问题 更多 >