顿顿锅包又
2021-02-05 16:13
采纳率: 66.7%
浏览 272

python相同key字典合并

从数据库中查询到几组数据

[{id:1,name:ab,role_id:1,fault_id:2},

{id:1,name:cd,role_id:2,fault_id:2},

{id:2,name:cc,role_id:1,fault_id:2},

{id:1,name:dd,role_id:1,fault_id:4},

{id:3,name:ab,role_id:1,fault_id:2}]

想根据id合并相同的 value 用\n分隔 

想等到的结果

[{id:1,name:ab\ncd\ndd,role_id:1\n2\n1},

{id:2,name:cc,role_id:1,fault_id:2},

{id:3,name:ab,role_id:1,fault_id:2}

]

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • Bryce__LY 2021-02-05 16:28
    已采纳
    data_list=[{'id':1,'name':'ab','role_id':1,'fault_id':2},
    
    {'id':1,'name':'cd','role_id':2,'fault_id':2},
    
    {'id':2,'name':'cc','role_id':1,'fault_id':2},
    
    {'id':1,'name':'dd','role_id':1,'fault_id':4},
    
    {'id':3,'name':'ab','role_id':1,'fault_id':2}]
    
    ret = []
    ret_id=[]
    for data in data_list:
         if data["id"] in ret_id:
              id_idx = ret_id.index(data["id"])
              current_dict = ret[id_idx]
              for key in current_dict.keys():
                   if key=="id":
                        continue
                   current_dict[key] = "{}\n{}".format(current_dict[key],data[key])
         else:
              ret.append(data)
              ret_id.append(data["id"])
    
    print(ret)
    已采纳该答案
    1 打赏 评论

相关推荐 更多相似问题