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

前端 未结 7 939
清歌不尽
清歌不尽 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:09

    One way to do that is:

    data = collections.defaultdict(list)
    for i in my_list:
        data[i['name']].append(i['score'])
    output = [{'name': i, 'score': max(j)} for i,j in data.items()]
    

    so output will be:

    [{'score': 2, 'name': 'Baz'},
     {'score': 3, 'name': 'Foo'},
     {'score': 3, 'name': 'Bar'}]
    

提交回复
热议问题