python list of dictionaries find duplicates based on value

后端 未结 3 1666
囚心锁ツ
囚心锁ツ 2020-12-10 07:34

I have a list of dicts in python 2.7.

a =[{\'id\': 1,\'desc\': \'smth\'},
    {\'id\': 2,\'desc\': \'smthelse\'},
    {\'id\': 1,\'desc\': \'smthelse2\'},
          


        
3条回答
  •  南笙
    南笙 (楼主)
    2020-12-10 07:49

    You can try:

    import operator, itertools
    
    key = operator.itemgetter('id')
    
    b = [{'id': x, 'desc': [d['desc'] for d in y]} 
         for x, y in itertools.groupby(sorted(a, key=key), key=key)]
    

提交回复
热议问题