Given a list of dictionaries, how can I eliminate duplicates of one key, and sort by another

前端 未结 7 901
清歌不尽
清歌不尽 2021-01-02 02:31

I\'m working with a list of dict objects that looks like this (the order of the objects differs):

[
    {\'name\': \'Foo\', \'score         


        
7条回答
  •  时光说笑
    2021-01-02 03:21

    In case you haven't heard of group by, this is nice use of it:

    from itertools import groupby
    
    data=[
        {'name': 'Foo', 'score': 1},
        {'name': 'Bar', 'score': 2},
        {'name': 'Foo', 'score': 3},
        {'name': 'Bar', 'score': 3},
        {'name': 'Foo', 'score': 2},
        {'name': 'Baz', 'score': 2},
        {'name': 'Baz', 'score': 1},
        {'name': 'Bar', 'score': 1}
    ]
    
    keyfunc=lambda d:d['name']
    data.sort(key=keyfunc)
    
    ans=[]
    for k, g in groupby(data, keyfunc):
        ans.append({k:max((d['score'] for d in g))})
    print ans
    
    >>>
    [{'Bar': 3}, {'Baz': 2}, {'Foo': 3}]
    

提交回复
热议问题