文章目录
- 一、数据:已知三个复杂字典列表如下
- 二、需求:将其转成最终数据结构如下
- 三、结构一 实现方法
- 四、结构二 实现方法
一、数据:已知三个复杂字典列表如下
list1 = [
{"lv_1": {"status": 2, "k_list": [{"k_id": 1, "k_name": "XXXXXXXXXX", "learn_time": 1, "wrong_num": 1},
{"k_id": 2, "k_name": "YYYYYYYYYY", "learn_time": 1, "wrong_num": 2}]}},
{"lv_1": {"status": 1, "k_list": [{"k_id": 3, "k_name": "ZZZZZZZZZZ", "learn_time": 0, "wrong_num": 0},
{"k_id": 4, "k_name": "PPPPPPPPPP", "learn_time": 0, "wrong_num": 0}]}}
]
list2 = [{"lv_2": {"all_num": 0, "error_num": 0, "status": -1}},
{"lv_2": {"status": 1, "all_num": 3, "error_num": 0}}]
list3 = [{"lv_3": {"all_num": 0, "error_num": 0, "status": -1}},
{"lv_3": {"status": 1, "all_num": 2, "error_num": 0}}]
二、需求:将其转成最终数据结构如下
![【工具封装】Python 合并复杂字典列表的几种形式_第1张图片](http://img.e-com-net.com/image/info8/79f7f7d51e8e4db0ac658cf256a86fbe.jpg)
![【工具封装】Python 合并复杂字典列表的几种形式_第2张图片](http://img.e-com-net.com/image/info8/4e4f502b699a4a808cc1960a9da0cc6e.jpg)
三、结构一 实现方法
import json
def merge_data(*args):
"""
将多个字典列表合并为一个字典列表
注意: 如果传入的参数长度不一,将以最短的长度合并
params:*args 至少一个不定长参数
"""
temp = []
for x in zip(*args):
d = dict()
for y in x:
d.update(y)
temp.append(d)
return temp
print(merge_data(list1, list2, list3))
========== 结果如下:==========
[
{
"lv_1":{
"status":2,
"k_list":[
{"k_id":1, "k_name":"XXXXXXXXXX", "learn_time":1, "wrong_num":1},
{"k_id":2, "k_name":"YYYYYYYYYY", "learn_time":1, "wrong_num":2}]
},
"lv_2":{"all_num":0, "error_num":0, "status":-1},
"lv_3":{"all_num":0, "error_num":0, "status":-1}
},
{
"lv_1":{
"status":1,
"k_list":[
{"k_id":3, "k_name":"ZZZZZZZZZZ", "learn_time":0, "wrong_num":0},
{"k_id":4, "k_name":"PPPPPPPPPP", "learn_time":0, "wrong_num":0}]
},
"lv_2":{"status":1, "all_num":3, "error_num":0},
"lv_3":{"status":1, "all_num":2, "error_num":0}
}
]
四、结构二 实现方法
def merge_data(*args):
"""
将多个字典列表合并为一个字典列表
注意: 如果传入的参数长度不一,将以最短的长度合并
params:*args 至少一个不定长参数
"""
temp = []
for x in zip(*args):
temp += list(x)
return temp
print(merge_data(list1, list2, list3))
========== 结果如下:==========
[
{
"lv_1":{
"status":2,
"k_list":[
{"k_id":1, "k_name":"XXXXXXXXXX", "learn_time":1, "wrong_num":1},
{"k_id":2, "k_name":"YYYYYYYYYY", "learn_time":1, "wrong_num":2}]
}
},
{
"lv_2":{"all_num":0, "error_num":0, "status":-1}
},
{
"lv_3":{"all_num":0, "error_num":0, "status":-1}
},
{
"lv_1":{
"status":1,
"k_list":[
{"k_id":3, "k_name":"ZZZZZZZZZZ", "learn_time":0, "wrong_num":0},
{"k_id":4, "k_name":"PPPPPPPPPP", "learn_time":0, "wrong_num":0}]
}
},
{
"lv_2":{"status":1, "all_num":3, "error_num":0}
},
{
"lv_3":{"status":1, "all_num":2, "error_num":0}
}
]