Summarize a list of dictionaries based on common key values

后端 未结 3 949
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-28 01:15

I have a list of dictionaries like so:

dictlist = [{\'day\': 0, \'start\': \'8:00am\', \'end\': \'5:00pm\'},
            {\'day\': 1, \'start\': \'10:00am\', \'e         


        
3条回答
  •  -上瘾入骨i
    2021-01-28 01:26

    You can use itertools.groupby like this.

    source code:

    from itertools import groupby
    for k, grp in groupby(sorted(dictlist, key=lambda x:(x['end'], x['start'])), key=lambda x:(x['start'], x['end'])):
        print [i['day'] for i in grp], k
    

    output:

    [5] ('11:00am', '1:00pm')
    [0, 2, 4] ('8:00am', '5:00pm')
    [1, 3] ('10:00am', '7:00pm')
    

    But I think using defaultdict(@Akavall answer) is the right way in this particular case.

提交回复
热议问题