简体   繁体   中英

how to merge values of python dict in a list of dictionaries

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?

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]}]

You can construct the entire the list of dictionaries as a single dictionary with multiple values, using defaultdict , like this

from collections import defaultdict
d = defaultdict(list)
for item in mylist:
    d[item['id']].append(item['value'])

And then using list comprehension, you can reconstruct the required list of dictionaries like this

print[{'id': key, 'value': d[key]} for key in d]
# [{'id':1, 'value':[4, 6]}, {'id':2, 'value':[6]}, {'id':3, 'value':[9,56,67]}]

您还可以使用 dict 理解:

newlist = {key: [entries[key] for entries in diclist] for key, value in diclist[0].items()}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM