Crazy Serb
Crazy Serb

Reputation: 76320

In Python how do I sort a list of dictionaries by a certain value of the dictionary + alphabetically?

Ok, here's what I'm trying to do... I know that itemgetter() sort could to alphabetical sort easy, 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 sorted alphabetically (by Name) + include the condition that the one with Name:'TOTAL' should be listed last in the sequence, like this:

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

How would I do that?

Upvotes: 3

Views: 1651

Answers (4)

Aaron Maenpaa
Aaron Maenpaa

Reputation: 122880

Use the key parameter of sort or sorted.

For example:

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}]

Upvotes: 0

Jarret Hardie
Jarret Hardie

Reputation: 97912

The best approach here is to decorate the sort key... Python will sort a tuple by the tuple components in order, so build a tuple key with your sorting criteria:

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

This results in a sort key of:

  • (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, the ones whose names aren't TOTAL will end up together, then be sorted alphabetically, and TOTAL will end up at the end.

Upvotes: 10

Mike Hordecki
Mike Hordecki

Reputation: 97101

Well, I would sort it in multiple passes, using list's sort method.

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')

Upvotes: -1

Dave
Dave

Reputation: 10577

>>> 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}]

Upvotes: 1

Related Questions