In Python, how to sort a list of dictionaries by a specific dictionary value + in alphabetical order?

Ok, here is what I'm trying to do ... I know that sorting itemgetter () may be in alphabetical order, but if I have something like this:

[{'Name': 'TOTAL', 'Rank': 100}, {'Name': 'Woo Company', 'Rank': 15}, {'Name': 'ABC Company', 'Rank': 20} ]

And I want it to be sorted alphabetically (by name) +, include the condition that the name with the name: "TOTAL" should be indicated last in the sequence, for example:

[{'Name': 'ABC Company', 'Rank': 20}, {'Name': 'Woo Company', 'Rank': 15}, {'Name': 'TOTAL', 'Rank': 100} ]

How can I do it?

+3
source share
4 answers

The best approach here is to decorate the sort key ... Python sorts the tuple with the tuple components in order, so create a tuple key with your sort criteria:

sorted(list_of_dicts, key=lambda d: (d['Name'] == 'TOTAL', d['Name'].lower()))

The result is a sort key:

  • (True, 'total') for {'Name': 'TOTAL', 'Rank': 100}
  • (False, 'woo company') for {'Name': 'Woo Company', 'Rank': 15}
  • (False, 'abc company') for {'Name': 'ABC Company', 'Rank': 20}

Since False sorts earlier than True, those whose names are not TOTAL are concatenated, then sorted alphabetically, and TOTAL ends at the end.

+10
>>> lst = [{'Name':'TOTAL', 'Rank':100}, {'Name':'Woo Company', 'Rank':15}, {'Name':'ABC Company', 'Rank':20}]
>>> lst.sort(key=lambda d: (d['Name']=='TOTAL',d['Name'].lower()))
>>> print lst
[{'Name': 'ABC Company', 'Rank': 20}, {'Name': 'Woo Company', 'Rank': 15}, {'Name': 'TOTAL', 'Rank': 100}]
+1

key .

:

dicts = [
     {'Name':'TOTAL', 'Rank':100}, 
     {'Name':'Woo Company', 'Rank':15},
     {'Name':'ABC Company', 'Rank':20}
]

def total_last(d):
    if d['Name'] == 'TOTAL':
        return '\xff\xff\xff\xff\xff\xff'
    return d['Name'].lower()

import pprint
pprint.pprint(sorted(dicts, key = total_last))

>python sort_dict.py
[{'Name': 'ABC Company', 'Rank': 20},
 {'Name': 'Woo Company', 'Rank': 15},
 {'Name': 'TOTAL', 'Rank': 100}]
0

, , .

list = [{'Name':'TOTAL', 'Rank':100}, {'Name':'Woo Company', 'Rank':15}, {'Name':'ABC Company', 'Rank':20}]

list.sort(key = lambda x: x['Name']) # Sorted by Name, alphabetically

list.sort(key = lambda x: 'b' if x['Name'] == 'TOTAL' else 'a')
-1
source

Source: https://habr.com/ru/post/1708903/


All Articles