python - 根据列表值将字典拆分为多个字典
问题描述
我正在使用嵌套的 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
这会为每个问题产生正确的字典:答案组合
解决方案
推荐阅读
- sql - 使用多个联合优化查询性能
- html - Postgresql Ltree 查询以获取嵌套 json/array 的评论线程并从中构建 HTML
- javascript - “webpack -p --mode production”不起作用
- regex - 正则表达式搜索 2 个最近的关键字
- reactjs - Uncaught TypeError: map is not a function In Reactjs with Firebase
- c++ - 为什么自动将此变量推断为双精度而不是浮点数?
- javascript - jQuery首先触发一个keydown事件
- python - CSV 文件在由 spark DataFrameWriter 创建时保持打开状态
- scala - 如何将案例类传递给函数参数并相应地获取模式?
- flutter - Flutter,DateTime.now() 在我的代码中不起作用