码迷,mamicode.com
首页 > 其他好文 > 详细

The Flat Dictionary

时间:2014-08-05 11:05:59      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:blog   io   for   ar   cti   代码   div   log   

The Flat Dictionary

原来的代码没处理dict为空的情况

 1 def flatten(dictionary):
 2     #[] is a list
 3     #() is a tuple
 4     stack = [((), dictionary)]
 5 
 6     result = {} #result is a dict
 7 
 8     while stack:
 9         path, current = stack.pop() #get a tuple
10 
11         for k, v in current.items(): #dict::items return key and values tuple
12             if isinstance(v, dict): #is a instance of dict
13                 stack.append((path + (k,), v)) #add key to tuple such as (xxx, yyy, zzz) and the element in stack is like ((xxx, yyy, zzz), value)
14             else:
15                 result["/".join((path + (k,)))] = v
16 
17         if len(current) == 0: #when the dict is empty
18             result["/".join(path)] = ""
19 
20     return result

(k,)一个元素的tuple

The Flat Dictionary,布布扣,bubuko.com

The Flat Dictionary

标签:blog   io   for   ar   cti   代码   div   log   

原文地址:http://www.cnblogs.com/hzhesi/p/3891625.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!