所以,我正在使用Django(Python),我想操纵序列化程序中的数据结构。
我有这个:
"week_task_schedule": [
{
"id": 3,
"week_number": 2,
"task": 1
},
{
"id": 2,
"week_number": 1,
"task": 2
},
{
"id": 1,
"week_number": 1,
"task": 1
}
]
我想得到这个:
"weeks": [
{
"week_number": 1,
"tasks": [
{
"id": 2,
"task": 2
},
{
"id": 1,
"task": 1
}
]
},
{
"week_number": 2,
"tasks": [
{
"id": 3,
"task": 1
}
]
}
]
我应该采取什么方法解决这个问题?
答案 0 :(得分:1)
使用for循环,您可以遍历结构并构建一个新版本,如:
def transform_data(data):
new_data = {}
for record in data:
new_data.setdefault(record['week_number'], []).append(
{k: v for k, v in record.items() if k != 'week_number'})
return [{'week_number': k, 'tasks': v} for k, v in new_data.items()]
这使用dict.setdefault
自动填充week_number
您还可以使用defaultdict
。在for
循环之后,list comprehension用于获取生成的dicts并创建所需的列表。
data = [
{
"id": 3,
"week_number": 2,
"task": 1
},
{
"id": 2,
"week_number": 1,
"task": 2
},
{
"id": 1,
"week_number": 1,
"task": 1
}
]
new_data = transform_data(data)
print(new_data)
[{'week_number': 2, 'tasks': [{'id': 3, 'task': 1}]},
{'week_number': 1, 'tasks': [{'id': 2, 'task': 2}, {'id': 1, 'task': 1}]}
]