简体   繁体   English

遍历嵌套字典的意外层

[英]Iterate through unexpected layers of a nested dictionary

So my situation is as follows. 所以我的情况如下。 I have a dictionary (shown below) of which I want to iterate through potentially large numbers of iterations, without having to manually define 'for i in dictionary[x][y][...]'. 我有一个字典(如下所示),我想对其进行潜在的大量迭代,而不必在字典中手动定义“ for i [x] [y] [...]”。 I intend to iterate through each layer and create a large string of html for other purposes. 我打算遍历每一层,并为其他目的创建一个大的html字符串。 For my dictionary there are potentially unknown amounts of subfolders and files, which is currently making it very hard to iterate through. 在我的字典中,可能存在未知数量的子文件夹和文件,这使迭代变得非常困难。

This is my dictionary 这是我的字典

{'A Folder': {
    'Another Folder': {
         'Stacked_File': 'secretid'
         'Another Stacked_File': 'anothersecretid'
    }

}, 'Another File':'moreids'...
}

Which I hope to convert to... 我希望转换为...

<ul>
    <ul>
        <i class="fi-folder"></i>&nbsp;&nbsp;A_Folder
    </ul>

    <br>

    <ul>
        <i class="fi-folder"></i>&nbsp;&nbsp;Another_Folder
        <ul>
            <ul>
                <i class="fi-folder"></i>&nbsp;&nbsp;Folder_Stacked
                <ul>
                    <ul><i class="fi-page"></i>&nbsp;&nbsp;Stacked_File
                    <ul><i class="fi-page"></i>&nbsp;&nbsp;Another_Stacked_File
                </ul>
            </ul>
        </ul>
    </ul>

How would I go about doing this? 我将如何去做呢?

Since you're looking at filesystems, if you're running this code on the system where the filesystem resides, you could handle it with recursion using os.listdir() and os.path.isdir(). 由于您正在查看文件系统,因此如果您在文件系统所在的系统上运行此代码,则可以使用os.listdir()和os.path.isdir()进行递归处理。 Here's a basic example: 这是一个基本示例:

def iter_folder(folder):
    if not os.path.isdir(folder):
        return
    print "folder: " + folder
    for item in os.listdir(folder):
        if os.path.isdir(item):
            iter_folder(item)
        else:
            print "file: " + item

It's hard for me to tell what you are actually trying to do with the output, but using recursion to flatten the nested dictionary is one good possibility: 对于我来说,很难说出您实际上要如何处理输出,但是使用递归来展平嵌套字典是一种很好的可能性:

d = {'A Folder': {
    'Another Folder': {
         'Stacked_File': 'secretid',
         'Another Stacked_File': 'anothersecretid'
    }

}, 'Another File':'moreids'
}

def nested_dict_flattener(d, level=0):
    l = []
    for k,v in d.items():
        if isinstance(v, basestring):
            l.append((level, k, v))
        elif isinstance(v, dict):
            l.append((level, k, 'START-FOLDER'))
            l.extend(nested_dict_flattener(v, level+1))
            l.append((level, k, 'END-FOLDER'))
    return l

import pprint
pprint.pprint( nested_dict_flattener(d) )

Output: 输出:

[(0, 'A Folder', 'START-FOLDER'),
 (1, 'Another Folder', 'START-FOLDER'),
 (2, 'Stacked_File', 'secretid'),
 (2, 'Another Stacked_File', 'anothersecretid'),
 (1, 'Another Folder', 'END-FOLDER'),
 (0, 'A Folder', 'END-FOLDER'),
 (0, 'Another File', 'moreids')]

Notice what's going on here: your nested dict s have been converted to a flat list of tuple s. 注意这里发生了什么:您嵌套的dict已转换为tuple s的平面列表。 You could then iterate through this list and look for the START-FOLDER / END-FOLDER markers to decide when to output opening and closing <ul> tags. 然后,您可以遍历此列表并查找START-FOLDER / END-FOLDER标记,以决定何时输出打开和关闭<ul>标签。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM