我应该如何解析 dict 对象? [英] How should I parse a dict object?
问题描述
我应该如何定义一个函数 parsedic()
像这样工作?
How should I define a function parsedic()
which works like?
dic={0:0,
1:{0:0,
1:1,
2:{0:0,},},
2:{0:{1:0,
0:{0:0}},},
3:0}
def parsedic(...):
...
print parsedic(dic)
结果:
0->0
3->0
1.0->0
1.1->1
1.2.0->0
2.0.0.0->0
2.0.1->0
dict的key的类型只能是数字或字符串,并且值只能是数字、字符串或字典.
The type of the key of the dict can only be a number or string, and the value can only be a number, string, or dict.
(为了避免误解,我删除了表明我如何试图解决这个问题很长时间的词.)
(To avoid misunderstandings, I deleted the words which showed how I've tried to solve this question for a long time.)
推荐答案
扁平化"dict 的最简单方法是这样的递归生成器:
The simplest way to "flatten" a dict is a recursive generator like this:
def parse(dic):
for k, v in dic.items():
if isinstance(v, dict):
for p in parse(v):
yield [k] + p
else:
yield [k, v]
lst = list(parse(dic))
这将创建一个列表[[key,key,key,value],[key,key,val] etc]
,例如:
This creates a list of lists [[key,key,key,value],[key,key,val] etc]
, for your example it will be:
[[0, 0], [1, 0, 0], [1, 1, 1], [1, 2, 0, 0], [2, 0, 0, 0, 0], [2, 0, 1, 0], [3, 0]]
要以所需格式打印,只需遍历此列表:
To print in the desired format just iterate over this list:
for row in parse(dic):
row = map(str, row)
print '.'.join(row[:-1]) + '->' + row[-1]
这回答了您的问题,但是如果您首先告诉我们您为什么需要这种转换,将会很有帮助.也许有更好的方法.
This answers your question, however it would be helpful if you tell us why you need this transformation in the first place. Maybe there's a better way.
这篇关于我应该如何解析 dict 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!