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

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

    Sorting is half the battle.

    import itertools
    import operator
    
    scores = [
        {'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}
    ]
    
    result = []
    sl = sorted(scores, key=operator.itemgetter('name', 'score'),
      reverse=True)
    name = object()
    for el in sl:
      if el['name'] == name:
        continue
      name = el['name']
      result.append(el)
    print result
    
    0 讨论(0)
提交回复
热议问题