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

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

    This is the simplest way I can think of:

    names = set(d['name'] for d in my_dicts)
    new_dicts = []
    for name in names:
        d = dict(name=name)
        d['score'] = max(d['score'] for d in my_dicts if d['name']==name)
        new_dicts.append(d)
    
    #new_dicts
    [{'score': 2, 'name': 'Baz'},
     {'score': 3, 'name': 'Foo'},
     {'score': 3, 'name': 'Bar'}]
    

    Personally, I prefer not to import modules when the problem is too small.

提交回复
热议问题