缩排嵌套词典每个级别的内容 [英] Indenting the contents of each level of a nested dictionary

查看:73
本文介绍了缩排嵌套词典每个级别的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a nested dictionary that contains bookmarks that were read from csv. Each level of nesting can have sub-folders and bookmarks. I need to make sure that I properly indent the sub-folders and bookmarks when I print them out. With my current code, all sub-folders are indented at the same level. This makes it appear as if my parent folder only has one level of nesting, but this is not the case. My bookmarks should have

我的代码是:

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 来检测确定每个嵌套文件夹所需的级别缩进

I used isinstance to determine the level indenting necessary for each nested folder

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')

这篇关于缩排嵌套词典每个级别的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆