Open In App

Sort a Dictionary - Python

Last Updated : 02 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, dictionaries store key-value pairs and are great for organizing data. While they weren’t ordered before Python 3.7, you can still sort them easily by keys or values, in ascending or descending order. Whether you’re arranging names alphabetically or sorting scores from highest to lowest, Python makes it simple with a few clean lines of code.

Sort a Dictionary by Keys

Let’s understand different methods to sort a dictionary by its keys. This is useful when you want the data in alphabetical or logical order based on the key names, making it easier to read or search through.

1. Using operator.itemgetter(0)

itemgetter function sort dictionary items by key (position 0 of each item). It’s explicit and clear when you want control over the sorting criteria.

Python
import operator

a = {"Gfg": 5, "is": 7, "Best": 2, "for": 9, "geeks": 8}
res = dict(sorted(a.items(), key=operator.itemgetter(0)))
print(res)

Output
{'Best': 2, 'Gfg': 5, 'for': 9, 'geeks': 8, 'is': 7}

Explanation: operator.itemgetter(0) specifies sorting by the dictionary key, which is at index 0 of each tuple in the dictionary items.

2. Using sorted() without key arguments

By default, sorted() sorts by the first item in each tuple, i.e., the key. It's the cleanest and most Pythonic way to sort a dictionary by keys.

Python
import operator

a = {"Gfg": 5, "is": 7, "Best": 2, "for": 9, "geeks": 8}
res = dict(sorted(a.items()))  # sorts by key by default
print(res)

Output
{'Best': 2, 'Gfg': 5, 'for': 9, 'geeks': 8, 'is': 7}

Explanation: sorted() sorts by the keys, which are the first elements in the dictionary items (tuples).

3. Using lambda

Lambda function accesses the key (item[0]) during sorting. It offers flexibility if you want to tweak the sorting logic later.

Python
import operator

a = {"Gfg": 5, "is": 7, "Best": 2, "for": 9, "geeks": 8}
res = dict(sorted(a.items(), key=lambda item: item[0]))
print(res)

Output
{'Best': 2, 'Gfg': 5, 'for': 9, 'geeks': 8, 'is': 7}

Explanation: lambda item: item[0] sorts the dictionary by the first element of each tuple (the key).

Sort a Dictionary by Values

Let’s understand different methods to sort a dictionary by its values. This is useful when you want the data arranged based on the values, such as sorting by scores, prices or any numerical data, making it easier to analyze or present.

1. Using operator.itemgetter(1)

Sorts the dictionary based on values (the second item in each tuple). Great when you want quick sorting without writing a custom function.

Python
import operator

a = {"Gfg": 5, "is": 7, "Best": 2, "for": 9, "geeks": 8}
res = dict(sorted(a.items(), key=operator.itemgetter(1)))
print(res)

Output
{'Best': 2, 'Gfg': 5, 'is': 7, 'geeks': 8, 'for': 9}

Explanation: operator.itemgetter(1) sorts the dictionary by the second element of each tuple (the value).

2. Using lambda function

Here, lambda item: item[1] targets the dictionary's values. It gives you more control, useful for adding custom sort logic later.

Python
import operator

a = {"Gfg": 5, "is": 7, "Best": 2, "for": 9, "geeks": 8}
res = dict(sorted(a.items(), key=lambda item: item[1]))
print(res)

Output
{'Best': 2, 'Gfg': 5, 'is': 7, 'geeks': 8, 'for': 9}

Explanation: lambda item: item[1] sorts the dictionary by the values.

Sort a Dictionary by values then keys

Sometimes, you may want to sort by values first and if values are equal, by keys. This ensures a consistent order, even with repeated values.

1. Using operator.iteemgetter(1,0)

Sorts first by value and if values are equal, then by key. This ensures a consistent order, even when values are repeated.

Python
import operator

a = {"Gfg": 5, "is": 7, "Best": 2, "for": 7, "geeks": 2}
res = dict(sorted(a.items(), key=operator.itemgetter(1, 0)))
print(res)

Output
{'Best': 2, 'geeks': 2, 'Gfg': 5, 'for': 7, 'is': 7}

Explanation: sorted() is applied to a.items(), which returns key-value tuples. Using operator.itemgetter(1, 0) as the key, it sorts first by value and then by key in case of ties. The sorted tuples are then converted back into a dictionary using dict().

2. Using lambda

Uses lambda item (item[1], item[0]) for multi-level sorting. Ideal for sorting with multiple criteria in a custom way.

Python
a = {"Gfg": 5, "is": 7, "Best": 2, "for": 7, "geeks": 2}
res = dict(sorted(a.items(), key=lambda item: (item[1], item[0])))
print(res)

Output
{'Best': 2, 'geeks': 2, 'Gfg': 5, 'for': 7, 'is': 7}

Explanation: lambda function as the key, it sorts first by value (item[1]) and then by key (item[0]) in case of ties. The sorted tuples are then converted back into a dictionary using dict().

3. Using dict comprehension

This method first sorts the dictionary using a lambda and then rebuilds it using dictionary comprehension. It’s concise, readable and ensures the result remains a proper dictionary structure.

Python
a = {"Gfg": 5, "is": 7, "Best": 2, "for": 7, "geeks": 2}
res = {k: v for k, v in sorted(a.items(), key=lambda item: (item[1], item[0]))}
print(res)

Output
{'Best': 2, 'geeks': 2, 'Gfg': 5, 'for': 7, 'is': 7}

Explanation: sorted() sorts key-value pairs by values (item[1]) and by keys (item[0]) if values are equal. The sorted tuples are then converted back into a dictionary using dictionary comprehension.

Sort in descending order

To sort a dictionary in descending order, use sorted() with reverse=True. For value-based sorting, add key=lambda item: item[1] to get highest values first great for scores or prices. For key-based sorting, just use reverse=True alone to order keys from Z to A.

Python
import operator
a = {"Gfg": 5, "is": 7, "Best": 2, "for": 9, "geeks": 8}

b = dict(sorted(a.items(), key=lambda item: item[1], reverse=True)) # By value
print(b)
c = dict(sorted(a.items(), reverse=True)) # By key
print(c)

Output
{'for': 9, 'geeks': 8, 'is': 7, 'Gfg': 5, 'Best': 2}
{'is': 7, 'geeks': 8, 'for': 9, 'Gfg': 5, 'Best': 2}

Explanation: reverse=True reverses the order. For value sorting, key=lambda item: item[1] ensures sorting is based on values.


Next Article
Practice Tags :

Similar Reads