【问题标题】:Python - create dynamic nested dictionary from list of dictionaryPython - 从字典列表创建动态嵌套字典
【发布时间】:2017-08-14 11:12:57
【问题描述】:

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

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(['standard','type'],result)

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

}

【问题讨论】:

  • 这是你的作业吗?
  • @wroniasty 我在思考逻辑时被卡住了,我尝试了几种方法,比如在 Python 中使用 group by 和过滤器。我想让它通用和动态,所以寻求帮助。我面临的主要问题是输出字典中的键是动态的。
  • 所需的输出结构中似乎有错误。您有一个未关闭的列表。请清理并澄清问题
  • @XeroSmith 我更新了问题。

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


【解决方案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 是您想要对结果进行分组的键。对每条记录的结果进行迭代 - 根据键值 (record[key]) 创建树结构。对于最后一个键 - 创建一个列表并将记录附加到它。

【讨论】:

  • 非常感谢,这工作得很好。你拯救了我的一天,谢谢。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-20
  • 2021-04-19
相关资源
最近更新 更多