I have list of dictionaries and every dictionary has property person_id
[{\'person_id\': 1, \'something..\': \'else\'}, {\'person_id\': 3, \'something..\': \'els
Your input isn't sorted by person_id
, so use a collections.defaultdict() approach with a loop:
from collections import defaultdict
grouped = defaultdict(list)
for person in inputlist:
grouped[person['person_id']].append(person)
grouped = grouped.values()
This sorts the input list into buckets, then places all the buckets back into an outer list. If you need the output to be sorted by id, you could use:
grouped = [grouped['pid'] for pid in sorted(grouped)]
If you need the original list in sorted order, or can produce it in sorted order, you can also use itertools.groupby() to do your grouping:
from itertools import groupby
from operator import itemgetter
grouped = [list(g) for p, g in groupby(inputlist, key=itemgetter('person_id'))]
but this does require that inputlist
is sorted first.