Nono.MA

Sort Python dictionaries by key

LAST UPDATED FEBRUARY 9, 2023

Here's how to sort a Python dictionary by a key, a property name, of its items. Check this post if you're looking to sort a list of lists instead.

# A list of people
people = [
    {'name': 'Nono', 'age': 32, 'location': 'Spain'},
    {'name': 'Alice', 'age': 20, 'location': 'Wonderland'},
    {'name': 'Phillipe', 'age': 100, 'location': 'France'},
    {'name': 'Jack', 'age': 45, 'location': 'Caribbean'},
]

# Sort people by age, ascending
people_sorted_by_age_asc = sorted(people, key=lambda x: x['age'])
print(people_sorted_by_age_asc)
# [
#     {'name': 'Alice', 'age': 20, 'location': 'Wonderland'},
#     {'name': 'Nono', 'age': 32, 'location': 'Spain'},
#     {'name': 'Jack', 'age': 45, 'location': 'Caribbean'},
#     {'name': 'Phillipe', 'age': 100, 'location': 'France'}
# ]

# Sort people by age, descending
people_sorted_by_age_desc = sorted(people, key=lambda x: -x['age'])
print(people_sorted_by_age_desc)
# [
#     {'name': 'Phillipe', 'age': 100, 'location': 'France'},
#     {'name': 'Jack', 'age': 45, 'location': 'Caribbean'},
#     {'name': 'Nono', 'age': 32, 'location': 'Spain'},
#     {'name': 'Alice', 'age': 20, 'location': 'Wonderland'}
# ]

# Sort people by name, ascending
people_sorted_by_name_desc = sorted(people, key=lambda x: x['name'])
print(people_sorted_by_name_desc)
# [
#     {'name': 'Alice', 'age': 20, 'location': 'Wonderland'},
#     {'name': 'Jack', 'age': 45, 'location': 'Caribbean'},
#     {'name': 'Nono', 'age': 32, 'location': 'Spain'},
#     {'name': 'Phillipe', 'age': 100, 'location': 'France'}
# ]

BlogCodePythonTil