【发布时间】:2016-08-03 15:31:09
【问题描述】:
我想遍历一个字典,它的值是列表、Unicode 字符串、字典、布尔值和整数的混合,以生成一个包含所有键值对的一维字典。我不在乎保留关联值为字典的键。
我尝试了递归函数,但缺少一些步骤。也许我需要在某处使用.update() 或+=?
def unravel(data):
resultsdict = {}
for k in data:
if isinstance(data[k],dict):
unravel(data[k])
else:
resultsdict[k] = data[k]
我的顶级字典值示例:
<type 'list'>
<type 'bool'>
<type 'dict'>
<type 'unicode'>
<type 'bool'>
<type 'unicode'>
<type 'dict'>
<type 'int'>
<type 'unicode'>
【问题讨论】:
-
似乎每次你深入研究这个递归函数时,你都在用 resultsdict = {} 重置字典。我认为这可能是个问题?
-
因此,对于包含在您的 dict 中的每个其他 dict,您想将该 dict 的内容移动到结构的根级别吗?例如。
{ 'a': { 'b': 'c'}, 'd': 'e' }变成{ 'b': 'c', 'd': 'e' }? -
@poke 你是对的
-
@Adib 也正确,也许我应该使用
yield?
标签: python recursion iteration