当前位置 : 主页 > 手机开发 > ROM >

如何合并列表中key相同的字典?

来源:互联网 收集:自由互联 发布时间:2021-06-10
现有list:list1 = [{a: 123}, {a: 456},{b: 789 }]合并成:list2 = [{a: [123,456]},{b: [789]}] from collections import defaultdictlst = [{ ‘ a ‘ : 123}, { ‘ a ‘ : 456},{ ‘ b ‘ : 789 }]dic = {} for _ in lst: for k, v in _.ite
现有list:

list1 = [{a: 123}, {a: 456},{b: 789}]

合并成:

list2 = [{a: [123,456]},{b: [789]}]

 

from collections import defaultdict
lst = [{a: 123}, {a: 456},{b: 789}]

dic = {}
for _ in lst:
    for k, v in _.items():
        dic.setdefault(k, []).append(v)

print [{k:v} for k, v in dic.items()]
上一篇:gevent实现异步
下一篇:绘制条形图
网友评论