原来的代码没处理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

相关文章:

  • 2021-07-19
  • 2022-12-23
  • 2021-10-07
  • 2022-01-12
  • 2021-07-11
  • 2022-12-23
  • 2022-12-23
  • 2021-09-17
猜你喜欢
  • 2022-12-23
  • 2021-07-04
  • 2021-05-27
  • 2021-12-31
  • 2021-11-18
  • 2022-02-20
  • 2022-12-23
相关资源
相似解决方案