首页 > 解决方案 > 根据列表值将字典拆分为多个字典

问题描述

我正在使用嵌套的 mongo 后端,并且正在将其映射到 SQL 数据库表。用户可以填写表单,这些表单将存储如下

{
  "response": {
    "question_1": "answer_1",
    "question_2": [
      "answer_a",
      "answer_b"
    ]
  },
  "user": "user_1",
  "form_id": "2344"
}

问题可以有多个答案存储为一个数组。我想把它展平成一个长格式(即每个问答组合一个记录),就像这样

[
{
  "question_id": "question_1",
  "answer": "answer_1",
  "user": "user_1",
  "form_id": "2344"
},
{
  "question_id": "question_2",
  "answer": "answer_a",
  "user": "user_1",
  "form_id": "2344"
},
{
  "question_id": "question_2",
  "answer": "answer_b",
  "user": "user_1",
  "form_id": "2344"
}
]

在 python 中实现这一目标的最有效方法是什么?我可以通过遍历响应字典中的每个响应来强制它,但我觉得这有点矫枉过正......

非常感谢

编辑:第一次工作尝试使用以下功能:

def transform_responses_to_long(completed_form: Dict):
    responses = completed_form["response"]
    del completed_form["response"]
    for key, values in responses.items():
        if not isinstance(values, (List, Dict)):
            values = [values]
        for value in values:
            result = {}
            result.update(completed_form)
            result.update({"question_id": key, "answer": value})
            yield result

这会为每个问题产生正确的字典:答案组合

标签: python

解决方案


推荐阅读