将深度很大的嵌套字典(森林)写入文本文件 [英] Writing nested dictionary (forest) of a huge depth to a text file

查看:99
本文介绍了将深度很大的嵌套字典(森林)写入文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个巨大的深度字典,代表森林(许多非二叉树),我要处理森林并创建一个具有森林所有可能关系的文本文件,例如给出字典:

I have a huge depth dictionary that represents forest (many non-binary trees) which I want to process the forest and create a text file with all possible relations of the forest, e.g. given the dictionary:

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

生成的文本文件如下所示:

the generated text file will look like:

a b c
a b d
a g

请注意,嵌套字典很大,并且递归对其进行迭代会导致内存运行时错误.

Note that the nested dictionary is big and iterating over it recursively is makes a memory run-time error.

我尝试做的是将字典递归转换为列表列表,这会产生运行时错误.代码:

What I tried doing is converting the dictionary into a list of lists recursively which yields a run-time error. The code:

def return_list(forest):
    for ent in forest.keys():
        lst = [new_ent] + grab_children(forest[ent])
        yield lst

def grab_children(father):
    local_list = []
    for key, value in father.items():
        local_list.append(new_key)
        local_list.extend(grab_children(value))
    return local_list

错误:在比较中超过了最大递归深度" RuntimeError

The error: "maximum recursion depth exceeded in comparison" RuntimeError

推荐答案

无递归,带有生成器和蹦床(写入文件):

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

文件包含:

a b c
a b d
a g

这篇关于将深度很大的嵌套字典(森林)写入文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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