dvas0004 / NerdNotes

A collection of notes: things I'd like to remember while reading technical articles, technical questions I couldn't answer, and so on.
11 stars 0 forks source link

Python: custom sorting #119

Open dvas0004 opened 4 years ago

dvas0004 commented 4 years ago

Python3 allows us to sort iterables using the sorted function. It also allows us to define a "key function". The key function accepts a single parameter - an item from the iterable. It returns an integer, the lower the integer, the higher up in the sorted list (i.e. an item which returns 1 will appear before an item which returns 2)

Let's define an iterable of dicts:

listOfDicts = [{
     'level': 'high',
     'id' : 3
 },
 {
     'level': 'low',
     'id' : 2
 },
 {
     'level': 'low',
     'id' : 1
 },
 {
     'level': 'medium',
     'id' : 4
}]

We'd like to have dicts whose level attribute is high to appear first in the list, followed by medium, and last by low. Let's define a suitable key function to do this:

def custom_sort_function(obj):
     if (obj['level'] == 'high'):
             return 1
     if (obj['level'] == 'medium'):
             return 2
     if (obj['level'] == 'low'):
             return 3
     return 4

Last, we apply the above function to our iterable using sorted. P.S. note how we use a lambda to feed each entry into the custom_sort_function - this is not necessary - you can just provide the function name

sorted(listOfDicts, key=lambda x : custom_sort_function(x))
# - OR -
sorted(listOfDicts, key=custom_sort_function)

Which returns the sorted list as expected:

[{'level': 'high', 'id': 3}, {'level': 'medium', 'id': 4}, {'level': 'low', 'id': 2}, {'level': 'low', 'id': 1}]