# 一、数据：已知三个复杂字典列表如下


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}}]



# 三、结构一 实现方法

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(json.dumps(d, ensure_ascii=False))    # JSON格式，保存数据库字段类型为JSON时会用到
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.extend(list(x))
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}
}
]



©️2019 CSDN 皮肤主题: 技术黑板 设计师: CSDN官方博客