简体   繁体   中英

Python - create dynamic nested dictionary from list of dictionary

Below is sample list data, I want to convert it into a dynamic dictionary.

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"
    }
]

I want to create one function conv_to_nested_dict(*args,data), which convertes all list of key to dictonary dynamically.

For example : conv_to_nested_dict(['standard','student'],result) should give op :

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

}

conv_to_nested_dict(['standard','type'],result)

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

}

This is a general idea.

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 is your source array, keys are the keys by which you want to group results. Iterate over results, for each record - create a tree structure based on key values ( record[key] ). For the last key - create a list and append the record to it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM