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 进行操作失败! 将字典放入集合中,集合只汲取字典的键(谁动了我的值)