a =[{'id':1,'gid1':1},{"id":2,"gid2":2},{"id":1,"gid3":3}]
b =[{"id":1,'gid1':1,'gid3':3},{"id":2,'gid2':2}]
代碼:
b = a.copy()# 對字典a進行淺複製
b =sorted(b,
key=lambda my_dict: my_dict['id'])# 根據b的id 進行排序
index =0while index <len(b)-1:if b[index]['id']== b[index +1]['id']:
b[index].update(b.pop(index+1))# 將要合併的字典直接pop()出來,然後和要合併相應的字典
index -=1
index +=1
遇到的問題及解答:
剛開始的想法是利用集合(集合內的元素不得重複),想把id1 和id2 進行像數據庫的group by 進行操作失敗! 將字典放入集合中,集合只汲取字典的鍵(誰動了我的值)