python - 将具有混合值的字典转换为平面字典

标签 python recursion iteration

我想遍历一个字典,它的值是列表、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/

相关文章:

javascript - 迭代表格的所有子元素并重置背景颜色

python - 不均匀(曲线)网格的 Matplotlib 流图

python - 通过 cron 运行时找不到带有 python 脚本的文件

javascript - 递归函数查找给定 id 的顶级父级

c++ - 在 C++ 中使用中序遍历对 BST 中的节点进行排序

python - 计算迭代操作百分比的最佳方法是什么?

c++ - C++-检查一个字符串数组是否包含另一个字符串的所有元素

python - 将 pandas DataFrame 中的相同连续值分组

python - 需要 Pandas 中的行值列表

postgresql - Postgres PL/pgSQL递归计算