我想遍历一个dict,其值是列表,unicode字符串,dict,bool和ints的混合,以生成具有所有键值对的一维dict。我不在乎保留关联值是字典的键。
我尝试了递归函数,但缺少一些步骤。也许我需要在某个地方使用.update()
或+=
?
def unravel(data):
resultsdict = {}
for k in data:
if isinstance(data[k],dict):
unravel(data[k])
else:
resultsdict[k] = data[k]
我的顶级dict值的示例:
<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/