首页 > 代码库 > The Flat Dictionary

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 tuple10 11         for k, v in current.items(): #dict::items return key and values tuple12             if isinstance(v, dict): #is a instance of dict13                 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,)))] = v16 17         if len(current) == 0: #when the dict is empty18             result["/".join(path)] = ""19 20     return result

(k,)一个元素的tuple