我想遍历一个字典,它的值是列表、unicode 字符串、字典、 bool 值和整数的混合,以生成一个包含所有键值对的一维字典。我不关心保留其关联值为字典的键。
我尝试了递归函数,但缺少一些步骤。也许我需要在某处使用 .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'>
最佳答案
你就快完成了,不过你需要返回创建的字典,并用递归调用的返回值更新字典:
def unravel (data):
d = {}
for k, v in data.items():
if isinstance(v, dict):
d.update(unravel(v))
else:
d[k] = v
return d
这样使用:
>>> unravel({ 'a': { 'b': 'c', 'd': 'e' }, 'f': 'g', 'h': { 'i': 'j' } })
{'f': 'g', 'i': 'j', 'b': 'c', 'd': 'e'}
关于python - 将具有混合值的字典转换为平面字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36583110/