如何在字典列表中合并python dict的值 [英] how to merge values of python dict in a list of dictionaries

查看:60
本文介绍了如何在字典列表中合并python dict的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字典的python列表,如下所示:

i have a python list of dictionary as shown below:

mylist = [{'id':1,'value':4},{'id':1,'value':6},{'id':2,'value':6},{'id':3,'value':9},{'id':3,'value':56},{'id':3,'value':67},]

我正在尝试通过对上面显示的词典列表进行一些操作来创建这样一个新的词典列表

i am trying to create a new list of dictionaries like this by doing some operations on the above shown list of dictionaries

newlist = [{'id':1,'value':[4,6]},{'id':2,'value':[6]},{'id':3,'value':[9,56,67]}]

有人知道这样做的好方法吗?

Does anyone know a good way to do this?

推荐答案

如果列表项按 id 排序,则可以使用

If list items are sorted by id, you can use itertools.groupby:

>>> mylist = [{'id':1,'value':4},{'id':1,'value':6},{'id':2,'value':6},{'id':3,'value':9},{'id':3,'value':56},{'id':3,'v    alue':67},]
>>> import itertools
>>> [{'id': key, 'value': [x['value'] for x in grp]}
...  for key, grp in itertools.groupby(mylist, key=lambda d: d['id'])]
[{'id': 1, 'value': [4, 6]},
 {'id': 2, 'value': [6]},
 {'id': 3, 'value': [9, 56, 67]}]

这篇关于如何在字典列表中合并python dict的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆