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

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

    There's no need for defaultdicts or sets here. You can just use dirt simple dicts and lists.

    Summarize the best running score in a dictionary and convert the result back into a list:

    >>> s = [
        {'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}
    ]
    >>> d = {}
    >>> for entry in s:
            name, score = entry['name'], entry['score']
            d[name] = max(d.get(name, 0), score)
    
    >>> [{'name': name, 'score': score} for name, score in d.items()]
    [{'score': 2, 'name': 'Baz'}, {'score': 3, 'name': 'Foo'}, {'score': 3, 'name': 'Bar'}]
    

提交回复
热议问题