# 原始数据 list1 = [ {"c_id": "101", "e_code": "201"}, {"c_id": "102", "e_code": "202"}, {"c_id": "103", "e_code": "201"}, {"c_id": "104", "e_code": "204"}, {"c_id": "105", "e_code": "204"}, ] # 变形后的目标数据 list2 = [ {'201': [{"c_id": "101", "e_code": "201"}, {"c_id": "103", "e_code": "201"}, ] }, {'202': [{"c_id": "102", "e_code": "202"}, ] }, {"204": [{"c_id": "104", "e_code": "204"}, {"c_id": "105", "e_code": "204"}, ] } ] e_code_val_list = [] new_data = [] # 遍历原始数据list1,获取e_code的值列表 for dict_new in list1: # print() for k, v in dict_new.items(): # print("%s=%s" % (k, v)) if k == "e_code": e_code_val_list.append(v) print("=========0==========") # "e_code"值去重 e_code_val_list = list(set(e_code_val_list)) print(e_code_val_list) print("=========1==========") # 根据e_code的值分类,遍历原始数据list1, for val in e_code_val_list: new_data.append({val: []}) print(new_data) print("=========2==========") # 构建目标数据 for dict_new in new_data: # print(dict) for k_e_c, v_list in dict_new.items(): # print(k_e_c) for dict_old in list1: # print(dict) for k, v in dict_old.items(): if k == "e_code" and v == k_e_c: dict_new[k_e_c].append(dict_old) print(new_data)
输出:
=========0========== ['204', '201', '202'] =========1========== [{'204': []}, {'201': []}, {'202': []}] =========2========== [{'204': [{'c_id': '104', 'e_code': '204'}, {'c_id': '105', 'e_code': '204'}]}, {'201': [{'c_id': '101', 'e_code': '201'}, {'c_id': '103', 'e_code': '201'}]}, {'202': [{'c_id': '102', 'e_code': '202'}]}]