代码之家  ›  专栏  ›  技术社区  ›  Akash

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

  •  1
  • Akash  · 技术社区  · 7 年前

    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\u to\u nested\u dict(*args,data),它将所有键列表动态转换为dictional。

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

    conv\u to\u nested\u dict(['standard','type',result)

    {
        "118": {
            "assessment": [{
                "score": 0,
                "student": "4"
            }]
        },
        "119": {
            "assignment": [{
                "score": 0,
                "student": "4"
            },{
                "score": 0,
                "student": "5"
            }]
        }
    
    }
    
    1 回复  |  直到 7 年前
        1
  •  3
  •   wroniasty    7 年前

    这是一个总体思路。

    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 是要根据其对结果进行分组的键。迭代结果,为每个记录创建基于键值的树结构(记录[key])。对于最后一个键,创建一个列表并将记录附加到其中。