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

时间:2017-08-14 11:12:57

标签: 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),它将所有键列表动态转换为dictonary。

例如:conv_to_nested_dict(['标准','学生'],结果)应该给出操作:

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

}

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

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

}

1 个答案:

答案 0 :(得分:1)

这是一个普遍的想法。

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是您希望对结果进行分组的键。迭代结果,对于每条记录 - 根据键值创建树结构(记录[键])。对于最后一个键 - 创建一个列表并将记录追加到它。