Group list of dictionaries to list of list of dictionaries with same property value

前端 未结 1 1733
一整个雨季
一整个雨季 2021-01-26 00:30

I have list of dictionaries and every dictionary has property person_id

[{\'person_id\': 1, \'something..\': \'else\'}, {\'person_id\': 3, \'something..\': \'els         


        
相关标签:
1条回答
  • 2021-01-26 01:08

    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.

    0 讨论(0)
提交回复
热议问题