首页 > 代码库 > 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。