Daily Grind 2: Python Sorting

Daily Grind 2: Python Sorting

I have only been recently getting into python – at first for fun on CodinGame, and then more recently for some side work (including the MailChimp integration).  Something that I often find necessary for the various CodinGame puzzles and contests is sorting lists and dictionaries.  I often have to look up the correct ways to sort, especially when my the lists or definitions contain more complicated objects.  I figured this would be a good opportunity to share some of what I’ve found.

Sorting Lists

a = [3,5,1,2,4]
print(a) #[1,2,3,4,5]

This is the most basic example.  Calling .sort on a list will update the list itself, and sort in a ascending order.  To sort descending, simply pass reverse=True, like so:

a = [3,5,1,2,4]
print(a) #[5,4,3,2,1]

The other option is to use the sorted method, which accepts any iterable.  The sorted method will not alter the list itself, but will instead return the resulting iterable.

a = [3,5,1,2,4]
b = sorted(a)
print(a) #[3,5,1,2,4]
print(b) #[1,2,3,4,5]
print(sorted(a, reverse=True)) #[5,4,3,2,1]

 Sorting Dictionaries

a = {'c': 2, 'b': 5, 'a': 3, 'e': 4, 'd': 1}
b = sorted(a)
print(b)    #['a','b','c','d','e']
print(b[0]) #a

In this case, sorting the dictionary a will result in a list that has they keys of the dictionary in ascending order.  If you want to sort the dictionary by value:

a = {'c': 2, 'b': 5, 'a': 3, 'e': 4, 'd': 1}
print(sorted(a, key=a.get)) #['d','c','a','e','b']

Notice that the result of the sort is still a list.  Sorting dictionaries results in lists – since the order of the dictionary itself does not matter.  Dictionaries are referenced directly by unordered keys, so if you want to get a sorted version of the dictionary, the result will be a list.

Sorting Objects

class SortableObject:
  def __init__(self, prop1, prop2):
    self.prop1 = prop1
    self.prop2 = prop2
  def __repr__(self):
    return repr((self.prop1, self.prop2))
listOfSortables = [
  SortableObject('andy', 5),
  SortableObject('chris', 3),
  SortableObject('bob', 8)

print(sorted(listOfSortables, key=lambda object: object.prop1)) #[('andy', 5), ('bob', 8), ('chris', 3)]
print(sorted(listOfSortables, key=lambda object: object.prop2)) #[('chris', 3), ('andy', 5), ('bob', 8)]

When it comes to sorting objects, most of the concepts are the same.  One key difference is that you have to specify which property on the object you want to sort the list by.  The example above shows the results when sorting the list by prop1 vs prop2.

Leave a Reply

Your email address will not be published. Required fields are marked *