How to Sort a Dictionary in Python
The fastest way to sort a dictionary in Python is
sorted()with alambda:
ordenado = dict(sorted(precios.items(), key=lambda item: item[1]))
When do you need this?
Dictionaries in Python do not have an inherent order, but since version 3.7 they keep the insertion order. You need to sort a dictionary in Python every time you want to rank results, show a ranking or process data in a specific order. In this guide you will learn how to do it by keys and by values.
Method 1: Sort a dictionary by keys
To sort a dictionary in Python by keys, use sorted() and rebuild the dictionary with a comprehension.
precios = {"pera": 3, "manzana": 1, "naranja": 2}
ordenado = {k: precios[k] for k in sorted(precios)}
print(ordenado)
# {'manzana': 1, 'naranja': 2, 'pera': 3}
Method 2: Sort by values with sorted() and lambda
To sort by values, use key=lambda item: item[1].
precios = {"pera": 3, "manzana": 1, "naranja": 2}
ordenado = dict(sorted(precios.items(), key=lambda item: item[1]))
print(ordenado)
# {'manzana': 1, 'naranja': 2, 'pera': 3}
The items() method returns pairs of key and value. The lambda tells sorted() which part of the pair to use as the sorting key.
Method 3: Use itemgetter instead of lambda
The operator.itemgetter function is faster and more readable when you need to sort by a specific position.
from operator import itemgetter
precios = {"pera": 3, "manzana": 1, "naranja": 2}
ordenado = dict(sorted(precios.items(), key=itemgetter(1)))
print(ordenado)
Method 4: Reverse order and lists of dictionaries
Add the reverse=True argument to sort from largest to smallest.
precios = {"pera": 3, "manzana": 1, "naranja": 2}
ordenado = dict(sorted(precios.items(), key=lambda item: item[1], reverse=True))
print(ordenado)
# {'pera': 3, 'naranja': 2, 'manzana': 1}
A very common case is to sort a list of dictionaries by one of their keys.
usuarios = [
{"nombre": "Ana", "edad": 25},
{"nombre": "Luis", "edad": 19},
{"nombre": "Carla", "edad": 30},
]
ordenado = sorted(usuarios, key=lambda u: u["edad"])
print(ordenado)
Method comparison
| Method | Advantage | When to use it |
|---|---|---|
sorted() by keys |
Simple for key order | When keys are the natural order |
sorted() + lambda |
Orders by value | Recommended for values |
itemgetter |
Faster and cleaner | Sorting by fixed positions |
reverse=True |
Largest to smallest | Rankings and top lists |
Common errors and solutions
Sorting the original dictionary by accident
sorted() never modifies the original dictionary. If your code changes it, you are probably assigning the result incorrectly. Always build a new dictionary with dict() or a comprehension.
Forgetting the key argument
Without key, sorted() compares the whole items. Use key=itemgetter(1) or key=lambda item: item[1] to order by value.
Frequently asked questions
Does sorted() modify the original dictionary?
No. sorted() returns a new sorted object. The original dictionary is not modified.
Can I sort by values without lambda?
Yes. You can use operator.itemgetter(1) as shown in Method 3.
Why do I need dict() around sorted()?
Because sorted() returns a list of pairs. The dict() constructor converts that list back into a dictionary.
Related content
- How to Remove Duplicates from a List in Python
- How to Convert String to Int in Python
- Python How-To Tutorials
- Python Course from Scratch
Related keywords
how to sort a dictionary in python, sort dictionary python, sort dict by value python, sorted lambda python, itemgetter python, sort list of dictionaries python, python dictionary
Save this tutorial and share it if it helped you. Find more practical guides in the Python how-to section.