The Flat Dictionary

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

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