缩进嵌套字典每一层的内容

Indenting the contents of each level of a nested dictionary

我有一个嵌套字典,其中包含从 csv 读取的书签。每个嵌套级别都可以有子文件夹和书签。我需要确保在打印子文件夹和书签时正确缩进它们。使用我当前的代码,所有子文件夹都缩进在同一级别。这使得我的父文件夹看起来好像只有一层嵌套,但事实并非如此。我的书签应该有

我的代码是:

with open('urls.csv') as bookmarks_input:
    reader = csv.DictReader(bookmarks_input)

    node = namedtuple('node', ['subtrees', 'bookmarks'])
    tree_t = lambda: node(defaultdict(tree_t), [])

    tree = tree_t()
    for entry in reader:
        t_cur = tree
        for level in entry['folder'].split('/'):
            t_cur = t_cur.subtrees[level]
        t_cur.bookmarks.append({'description': entry['friendly'], 'ur': entry['url']})


def extract_data(folder, sub_ts, indent=2):

    print('\t' * indent, f'<DT><H3>{folder}</H3>')
    print('\t' * indent, f'<DL><p>')
    bookmarks_list = sub_ts.bookmarks

    if sub_ts.subtrees:
        st_indent = 3
        for k, v in sub_ts.subtrees.items():
            extract_data(k, v, st_indent)
            st_indent += 1
    if bookmarks_list:
        for bookmarks_dict in bookmarks_list:
            description, ur = bookmarks_dict['description'], bookmarks_dict['ur']
            print('\t' * (indent + 2), f'<DT><A HREF="{ur}">{description}</A>')
    print('\t' * indent, f'</DL><p>')


print(html_head)
for name, subtree in tree.subtrees.items():
    extract_data(name, subtree)
print(html_tail)

示例 CSV 为:

friendly,url,folder
CUCM - North,cucm-n.acme.com,ACME/CUCM/North
CUCM - PUB,cucm-pub.acme.com,ACME/CUCM
UCCX - South,uccx-south.acme.com,ACME/UCCX/South
UCCX - North,uccx-north.acme.com,ACME/UCCX/North
UCCX - PUB,uccx-pub.acme.com,ACME/UCCX
Database,db.acme.com,ACME
CUCM - North2,cucm-n2.acme.com,ACME/CUCM/North

我使用 isinstance 来确定每个嵌套文件夹所需的缩进级别

def extract_data(nested_dicts, indent=2):
    for folder, nested_dict in nested_dicts.items():
        bookmarks_list = nested_dict.bookmarks

        html_file.write('\t' * indent + f'<DT><H3>{folder}</H3>\n')
        html_file.write('\t' * indent + f'<DL><p>\n')
        if isinstance(nested_dict, node):
            extract_data(nested_dict.subtrees, indent + 1)

        if bookmarks_list:
            for bookmarks_dict in bookmarks_list:
                description, ur = bookmarks_dict['description'], bookmarks_dict['ur']
                html_file.write('\t' * (indent + 1) + f'<DT><A HREF="http://{ur}">{description}</A>\n')
        html_file.write('\t' * indent + f'</DL><p>\n')