8 Advanced Python Tricks Used by Seasoned Programmers
1. Sorting Objects by Multiple Keys

Suppose we want to sort the following list of dictionaries:

people = [

{ 'name': 'John', "age": 64 },

{ 'name': 'Janet', "age": 34 },

{ 'name': 'Ed', "age": 24 },

{ 'name': 'Sara', "age": 64 },

{ 'name': 'John', "age": 32 },

{ 'name': 'Jane', "age": 34 },

{ 'name': 'John', "age": 99 },

]

But we don’t just want to sort it by name or age, we want to sort it by both fields. In SQL, this would be a query like:

SELECT * FROM people ORDER by name, age

There’s actually a very simple solution to this problem, thanks to Python’s guarantee that sort functions offer a stable sort order. This means items that compare equal retain their original order.

To achieve sorting by name and age, we can do this:

import operator

people.sort(key=operator.itemgetter('age'))

people.sort(key=operator.itemgetter('name'))

Notice how I reversed the order. We first sort by age, and then by name. With operator.itemgetter() we get the age and name fields from each dictionary inside the list in a concise way.

This gives us the result we were looking for:

[

{'name': 'Ed', 'age': 24},

{'name': 'Jane', 'age': 34},

{'name': 'Janet','age': 34},

{'name': 'John', 'age': 32},

{'name': 'John', 'age': 64},

{'name': 'John', 'age': 99},

{'name': 'Sara', 'age': 64}

]

The names are sorted primarily, the ages are sorted if the name is the same. So all the Johns are grouped together, sorted by age.

Inspired by this StackOverflow question.
['Erik Van Baaren']
['Technology', 'Software Development', 'Learning To Code', 'Python', 'Programming']