Python-从字典列表创建动态嵌套字典

标签 python python-2.7 python-3.x recursive-datastructures

下面是示例列表数据,我想将其转换为动态字典。

result = [
    {
        "standard": "119",
        "score": "0",
        "type": "assignment",
        "student": "4"
    },
    {
        "standard": "119",
        "score": "0",
        "type": "assignment",
        "student": "5"
    },
    {
        "standard": "118",
        "score": "0",
        "type": "assessment",
        "student": "4"
    }
]

我想创建一个函数 conv_to_nested_dict(*args,data),它将所有键列表动态转换为字典。

例如: conv_to_nested_dict(['standard','student'],result) 应该给出 op :

{
    "118": {
        "4": [{
            "score": "0",
            "type": "assessment"
        }]
    },
    "119": {
        "4": [{
            "score": "0",
            "type": "assignment"
        }],
        "5": [{
            "score": "0",
            "type": "assignment"
        }]
    }

}

conv_to_nested_dict(['标准','类型'],结果)

{
    "118": {
        "assessment": [{
            "score": 0,
            "student": "4"
        }]
    },
    "119": {
        "assignment": [{
            "score": 0,
            "student": "4"
        },{
            "score": 0,
            "student": "5"
        }]
    }

}

最佳答案

这是一个总体想法。

def conf_to_nested_dict(keys, result):
    R = {}
    for record in result: 
        node = R
        for key in keys[:-1]:
            kv = record[key]
            next_node = node.get(kv, {})
            node[kv] = next_node
            node = next_node
        last_node = node.get(record[keys[-1]], [])
        last_node.append(record)
        node[record[keys[-1]]] = last_node


    return R

#R is your structure

result 是您的源数组,keys 是您想要对结果进行分组的键。对于每条记录,迭代结果 - 基于键值 ( record[key] ) 创建树结构。对于最后一个键 - 创建一个列表并将记录附加到其中。

关于Python-从字典列表创建动态嵌套字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45673242/

相关文章:

python - Cython 优化 numpy 数组求和的关键部分

python - 特别是本地 Django 部署。织物?

python - 如何让 Tornado 在 ssh 连接断开时不停止?

python-3.x - 无法导入torchvision --AttributeError : module 'torch.jit' has no attribute 'unused' . Windows10,Python 3.7

python - 无法从网页获取动态生成的内容

python - 使用 np.newaxis 计算平方差之和

python - 取消 pandas 数据框时出错

macos - 找不到 Pelican 插件

python-3.x - 基于Python中的值对无向图的节点进行排序

Python从文件中删除一行行