Writing nested dictionary (forest) of a huge depth to a text file

醉酒当歌 提交于 2019-12-05 23:08:39

Without recursion, with generator and trampoline (with writing to file):

data = {'a': {'b': {'c': {}, 'd': {}}, 'g': {}}}


def write_dict(d, s=(), f_out=None):
    if len(d) == 0:
        if f_out:
            f_out.write(' '.join(s) + '\n')
        return

    for k, v in reversed(list(d.items())):
        yield write_dict, v, s + (k, ), f_out


with open('data_out.txt', 'w') as f_out:

    stack = [write_dict(data, f_out=f_out)]

    while stack:
        try:
            v = next(stack[-1])
        except StopIteration:
            del stack[-1]
            continue

        stack.insert(-1, v[0](v[1], v[2], v[3]))

The file contains:

a b c
a b d
a g
def l(d):
    return '\n'.join(k + (i and ' ' + i) for k, v in d.items() for i in l(v).split('\n'))
print(l({'a': {'b': {'c': {}, 'd': {}}, 'g': {}}}))

This outputs:

a b c
a b d
a g

A non-recursive approach:

d = {'a': {'b': {'c': {}, 'd': {}}, 'g': {}}}
p = q = []
while True:
    for k, v in d.items():
        if v:
            q.append((v, p + [k]))
        else:
            print(' '.join(p + [k]))
    if not q:
        break
    d, p = q.pop(0)

This outputs:

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