Sort a Dictionary - Python
Last Updated :
02 May, 2025
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.
Related Articles
Similar Reads
Sort Python Dictionary by Value
Python dictionaries are versatile data structures that allow you to store key-value pairs. While dictionaries maintain the order of insertion. sorting them by values can be useful in various scenarios. In this article, we'll explore five different methods to sort a Python dictionary by its values, a
3 min read
Python - Sorting a dictionary of tuples
This task becomes particularly useful when working with structured data, where tuples represent grouped information (e.g., names and scores, items and prices). Sorting such data enhances its readability and usability for further analysis.For example, consider a dictionary d = {'student3': ('bhanu',
3 min read
Python - Sort Dictionaries by Size
Given a Dictionary List, perform sort by size of dictionary. Input : test_list = [{4:6, 9:1, 10:2, 2:8}, {4:3, 9:1}, {3:9}, {1:2, 9:3, 7:4}] Output : [{3: 9}, {4: 3, 9: 1}, {1: 2, 9: 3, 7: 4}, {4: 6, 9: 1, 10: 2, 2: 8}] Explanation : 1 < 2 < 3 < 4, sorted by number of keys of dictionary. In
4 min read
Python - Rotate dictionary by K
Given a dictionary perform its reordering by right rotating dictionary keys by K. Examples: Input : test_dict = {1:6, 8:1, 9:3, 10:8, 12:6, 4:9}, K = 2 Output : {12: 6, 4: 9, 1: 6, 8: 1, 9: 3, 10: 8} Explanation : After right rotation ( cyclic ) by 2 elements, items are re-arranged. Input : test_dic
4 min read
Python | Sort nested dictionary by key
Sorting has quite vivid applications and sometimes, we might come up with a problem in which we need to sort the nested dictionary by the nested key. This type of application is popular in web development as JSON format is quite popular. Let's discuss certain ways in which this can be performed. Met
4 min read
Python - Sort List by Dictionary values
Sometimes while working with a Python dictionary, we can have problems in which we need to perform a sort of list according to the corresponding value in the dictionary. This can have applications in many domains, including data and web development. Let's discuss certain ways in which this task can
3 min read
Python - Sort Dictionary ignoring Key
Sometimes, while working with Python dictionaries, we can have problem in which we need to perform sorting of dictionary elements. This is quite straight forward, but sometimes, we can have certain stray keys, which we don't wish to alter order while sorting. This works for Python >= 3.6 as keys
6 min read
Python | Sort dictionary keys to list
Sometimes, we wish to flatten the dictionary into list, the simple flattening is relatively easier, but when we wish to align keys and values in sorted way, i.e sorted by value, then it becomes quite a complex problem. Let's discuss certain ways in which this task can be performed. Method #1 : Using
4 min read
Python - Sort Dictionary by Values and Keys
Given a dictionary, sort according to descended values, if similar values, then by keys lexicographically. Input : test_dict = {"gfg" : 1, "is" : 1, "best" : 1, "for" : 1, "geeks" : 1} Output : {"best" : 1, "is" : 1, "for" : 1, "geeks" : 1, "gfg" : 1} Explanation : All values are equal, hence lexico
3 min read
Python - Sort Dictionary key and values List
Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform the sorting of it, wrt keys, but also can have a variation in which we need to perform a sort on its values list as well. Let's discuss certain way in which this task can be performed. Input : test_d
6 min read