Tip: Sort Python dictionary list using a tuple key

Python, List, Dictionary · Jan 4, 2023

Sorting a list of dictionaries in Python can seem intimidating at first. This is especially true if you want to sort using multiple keys. Luckily, the sorted() function can be used to sort a list of dictionaries using a tuple key. Simply return a tuple with the order of keys you want to sort by and the sorted() function will do the rest.

friends =  [
  {"name": "John", "surname": "Doe", "age": 26},
  {"name": "Jane", "surname": "Doe", "age": 28},
  {"name": "Adam", "surname": "Smith", "age": 30},
  {"name": "Michael", "surname": "Jones", "age": 28}
]

print(
  sorted(
    friends,
    key=lambda friend:
    (friend["age"], friend["surname"], friend["name"])
  )
)
# PRINTS:
# [
#   {'name': 'John', 'surname': 'Doe', 'age': 26},
#   {'name': 'Jane', 'surname': 'Doe', 'age': 28},
#   {'name': 'Michael', 'surname': 'Jones', 'age': 28},
#   {'name': 'Adam', 'surname': 'Smith', 'age': 30}
# ]

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub.

More like this

  • Python Dictionaries

    A snippet collection of dictionary helpers and tips for Python 3.6.

    Collection · 24 snippets

  • What are named tuples in Python?

    Understand Python's named tuples and start using them in your projects today.

    Python, List · Jun 12, 2021

  • Lists to dictionary

    Combines two lists into a dictionary, using the first one as the keys and the second one as the values.

    Python, List · Nov 2, 2020

  • Map list to dictionary

    Maps the values of a list to a dictionary using a function.

    Python, List · Nov 2, 2020