问题描述
继续我的上一个问题:
嵌套字典很大,并对其进行递归迭代使得内存运行时错误,因此最好使用此问题开头的链接中的生成器样式解决方案。
d = {'a':{'b':{'c':{'x':{}},'d':{'p':{}}},'g ':{},'f':{}},'t':{'r':{'o':{}},'y':{}}}
with open('file', 'w')as f:r,
,d.items()中的s:
q = []
p = r
而True:
for k,v在s.items()中:
f.write('(%s,%s)'%(如果p == r else p,k)是'ROOT')如果v:
q.append((k,v))
如果不是q:
break
p,s = q.pop(0)
f.write('\n' )
此输出:
(ROOT,b)(ROOT,g)(ROOT,f)(b ,c)(b,d)(c,x)(d,p)
(ROOT,r)(ROOT,y)(r,o)
Continued to my older question:Writing nested dictionary (forest) of a huge depth to a text file
Now I want to write the forest traversal in the BFS style: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 the sequences of (father, son) relations from the forest, i.e. given the dictionary:
{'a': {'b': {'c': {'x': {}}, 'd': {'p': {}}}, 'g': {}, 'f': {}},
't': {'r': {'o': {}}, 'y': {}}}
the generated text file will look like:
(ROOT,b) (ROOT,g) (ROOT,f) (b,c) (b,d) (c,x) (d,p) \n
(ROOT,r) (ROOT,y) (r,o) \n
Note that I replaces all the roots in the forest with the word "ROOT".
Here is a simple visualization of the forest:
The nested dictionary is big and iterating over it recursively makes a memory run-time error, so a "Generator style" solution as in the link at the beginning of this question would be the best.
d = {'a': {'b': {'c': {'x': {}}, 'd': {'p': {}}}, 'g': {}, 'f': {}}, 't': {'r': {'o': {}}, 'y': {}}}
with open('file', 'w') as f:
for r, s in d.items():
q = []
p = r
while True:
for k, v in s.items():
f.write('(%s,%s) ' % ('ROOT' if p == r else p, k))
if v:
q.append((k, v))
if not q:
break
p, s = q.pop(0)
f.write('\n')
This outputs:
(ROOT,b) (ROOT,g) (ROOT,f) (b,c) (b,d) (c,x) (d,p)
(ROOT,r) (ROOT,y) (r,o)
这篇关于以BFS样式将深度很大的嵌套字典(森林)写入文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!