Indenting the contents of each level of a nested dictionary

﹥>﹥吖頭↗ 提交于 2019-12-08 11:22:54

问题


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

My code is:

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)

Sample CSV is:

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

回答1:


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


来源:https://stackoverflow.com/questions/57512098/indenting-the-contents-of-each-level-of-a-nested-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!