Python 3.7+ or CPython 3.6

Dicts preserve insertion order in Python 3.7+. Same in CPython 3.6, but it's an implementation detail.

>>> x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
>>> {k: v for k, v in sorted(x.items(), key=lambda item: item[1])}
{0: 0, 2: 1, 1: 2, 4: 3, 3: 4}

or

>>> dict(sorted(x.items(), key=lambda item: item[1]))
{0: 0, 2: 1, 1: 2, 4: 3, 3: 4}

Older Python

It is not possible to sort a dictionary, only to get a representation of a dictionary that is sorted. Dictionaries are inherently orderless, but other types, such as lists and tuples, are not. So you need an ordered data type to represent sorted values, which will be a list—probably a list of tuples.

For instance,

import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(1))

sorted_x will be a list of tuples sorted by the second element in each tuple. dict(sorted_x) == x.

And for those wishing to sort on keys instead of values:

import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(0))

In Python3 since unpacking is not allowed we can use

x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=lambda kv: kv[1])

If you want the output as a dict, you can use collections.OrderedDict:

import collections

sorted_dict = collections.OrderedDict(sorted_x)
Answer from Devin Jeanpierre on Stack Overflow
Top answer
1 of 16
7099

Python 3.7+ or CPython 3.6

Dicts preserve insertion order in Python 3.7+. Same in CPython 3.6, but it's an implementation detail.

>>> x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
>>> {k: v for k, v in sorted(x.items(), key=lambda item: item[1])}
{0: 0, 2: 1, 1: 2, 4: 3, 3: 4}

or

>>> dict(sorted(x.items(), key=lambda item: item[1]))
{0: 0, 2: 1, 1: 2, 4: 3, 3: 4}

Older Python

It is not possible to sort a dictionary, only to get a representation of a dictionary that is sorted. Dictionaries are inherently orderless, but other types, such as lists and tuples, are not. So you need an ordered data type to represent sorted values, which will be a list—probably a list of tuples.

For instance,

import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(1))

sorted_x will be a list of tuples sorted by the second element in each tuple. dict(sorted_x) == x.

And for those wishing to sort on keys instead of values:

import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(0))

In Python3 since unpacking is not allowed we can use

x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=lambda kv: kv[1])

If you want the output as a dict, you can use collections.OrderedDict:

import collections

sorted_dict = collections.OrderedDict(sorted_x)
2 of 16
1650

As simple as: sorted(dict1, key=dict1.get)

Well, it is actually possible to do a "sort by dictionary values". Recently I had to do that in a Code Golf (Stack Overflow question Code golf: Word frequency chart). Abridged, the problem was of the kind: given a text, count how often each word is encountered and display a list of the top words, sorted by decreasing frequency.

If you construct a dictionary with the words as keys and the number of occurrences of each word as value, simplified here as:

from collections import defaultdict
d = defaultdict(int)
for w in text.split():
    d[w] += 1

then you can get a list of the words, ordered by frequency of use with sorted(d, key=d.get) - the sort iterates over the dictionary keys, using the number of word occurrences as a sort key.

for w in sorted(d, key=d.get, reverse=True):
    print(w, d[w])

or, if we want a dictionary back (since Python 3.6+ preserves insertion order):

{w: d[w] for w in sorted(d, key=d.get, reverse=True)}

I am writing this detailed explanation to illustrate what people often mean by "I can easily sort a dictionary by key, but how do I sort by value" - and I think the original post was trying to address such an issue. And the solution is to do sort of list of the keys, based on the values, as shown above.

🌐
OneUptime
oneuptime.com › home › blog › how to sort a dictionary by value in python
How to Sort a Dictionary by Value in Python
January 25, 2026 - Often you only need the highest or lowest values. scores = {'Alice': 85, 'Bob': 92, 'Charlie': 78, 'Diana': 95, 'Eve': 88} # Top 3 scores top_3 = dict(sorted(scores.items(), key=lambda x: x[1], reverse=True)[:3]) print(top_3) # {'Diana': 95, 'Bob': 92, 'Eve': 88} # Bottom 3 scores bottom_3 = dict(sorted(scores.items(), key=lambda x: x[1])[:3]) print(bottom_3) # {'Charlie': 78, 'Alice': 85, 'Eve': 88} For large dictionaries, heapq.nlargest and heapq.nsmallest are more efficient when you only need a few items.
Discussions

Sorting a dict by its values
Hi everyone I’ve been trying to come up with the most efficient way to sort a dictionary by its values but since there aren’t any sorting methods for a dictionary, I’ve been struggling l to do so. Any ideas? Thx More on discuss.python.org
🌐 discuss.python.org
14
0
October 3, 2023
python - Sort dictionary of dictionaries by value - Stack Overflow
I saw this post, but I'm not sure ... of dictionaries. ... Would something like this work? Similar to the post you linked, this uses the key function of sorted to provide a custom sort order. iteritems() returns a (key, value) tuple, so that gets passed into lambda (x, y): y['position'], where y['position'] is the value (your nested dictionary, keyed by the status), ... More on stackoverflow.com
🌐 stackoverflow.com
Sorting dict keys and a dict inside a dict
Dictionaries are not sortable. They preserve insertion order only. If you need sorted data, use a different data structure. More on reddit.com
🌐 r/learnpython
30
47
July 4, 2022
How to sort a list containing dictionary items?
List objects have a sort function to sort the list in-place. This function has a key parameter to specify a function that will be called on each item in the list, after which the items will be sorted based on the results of that function. It also accepts a reverse parameter that, if set to True, will cause sort to sort the list in descending order. Let's say you have a list students that contains Student objects. To sort the students by age from oldest to youngest, you'd do students.sort(key = lambda x: x.Age, reverse=True). Sorting your list of dictionaries is done in pretty much the same way. See this if you need more examples. Keep in mind that in your list, the currency values are strings, not integers. You'll need to convert them first, otherwise they won't be sorted correctly. You can do that in the lambda function you pass to sort. Incidentally, using variable names like list is bad practice. You're overriding the built-in list class by doing that. More on reddit.com
🌐 r/learnpython
4
2
September 30, 2023
🌐
freeCodeCamp
freecodecamp.org › news › sort-dictionary-by-value-in-python
Sort Dictionary by Value in Python – How to Sort a Dict
September 13, 2022 - We’ve just had our cake and ate it as well! Remember the sorted() method accepts a third value called reverse. reverse with a value of True will arrange the sorted dictionary in descending order.
🌐
Python.org
discuss.python.org › python help
Sorting a dict by its values - Python Help - Discussions on Python.org
October 3, 2023 - Hi everyone I’ve been trying to come up with the most efficient way to sort a dictionary by its values but since there aren’t any sorting methods for a dictionary, I’ve been struggling l to do so. Any ideas? Thx
🌐
DataCamp
datacamp.com › tutorial › sort-a-dictionary-by-value-python
How to Sort a Dictionary by Values in Python | DataCamp
June 19, 2024 - A2: To sort a dictionary with nested dictionaries, we need to define a custom sorting function that extracts and compares the relevant nested values. This requires a more complex lambda function or a separate function to handle the comparison. A3: No, dictionaries in Python are inherently unordered collections as of versions before 3.7, and even though they maintain insertion order from Python 3.7 onwards, there is no built-in method to sort them in-place.
Top answer
1 of 4
40

Would something like this work? Similar to the post you linked, this uses the key function of sorted to provide a custom sort order. iteritems() returns a (key, value) tuple, so that gets passed into lambda (x, y): y['position'], where y['position'] is the value (your nested dictionary, keyed by the status), and position is the item by which you want to sort.

In [35]: statuses = {
            'pending' : {'status_for':'all', 'position':1},
            'cancelled' : {'status_for':'all','position':2},
            'approved' : {'status_for':'owner', 'position':1},
            'rejected - owner' : {'status_for':'owner', 'position':2},
            'accepted' : {'status_for':'dev', 'position':1},
            'rejected - developer' : {'status_for':'dev', 'position':3},
            'closed' : {'status_for':'dev', 'position':5},
            }

In [44]: for s in sorted(statuses.iteritems(), key=lambda (x, y): y['position']):
   ....:     print s
   ....:
   ....:
('accepted', {'position': 1, 'status_for': 'dev'})
('approved', {'position': 1, 'status_for': 'owner'})
('pending', {'position': 1, 'status_for': 'all'})
('rejected - owner', {'position': 2, 'status_for': 'owner'})
('cancelled', {'position': 2, 'status_for': 'all'})
('rejected - developer', {'position': 3, 'status_for': 'dev'})
('closed', {'position': 5, 'status_for': 'dev'})
2 of 4
11
In [232]: statuses = {                                                                  
            'pending' : {'status_for':'all', 'position':1},
            'cancelled' : {'status_for':'all','position':2},
            'approved' : {'status_for':'owner', 'position':1},
            'rejected - owner' : {'status_for':'owner', 'position':2},
            'accepted' : {'status_for':'dev', 'position':1},
            'rejected - developer' : {'status_for':'dev', 'position':3},
            'closed' : {'status_for':'dev', 'position':5},
            }

In [235]: sorted(statuses,key=lambda x:statuses[x]['position'])
Out[235]: 
['accepted',
 'approved',
 'pending',
 'rejected - owner',
 'cancelled',
 'rejected - developer',
 'closed']

or using operator.getitem():

In [260]: from operator import *

In [261]: sorted(statuses.items(),key=lambda x:getitem(x[1],'position'))
Out[261]: 
[('accepted', {'position': 1, 'status_for': 'dev'}),
 ('approved', {'position': 1, 'status_for': 'owner'}),
 ('pending', {'position': 1, 'status_for': 'all'}),
 ('rejected - owner', {'position': 2, 'status_for': 'owner'}),
 ('cancelled', {'position': 2, 'status_for': 'all'}),
 ('rejected - developer', {'position': 3, 'status_for': 'dev'}),
 ('closed', {'position': 5, 'status_for': 'dev'})]
Find elsewhere
🌐
Stack Abuse
stackabuse.com › how-to-sort-dictionary-by-value-in-python
How to Sort a Dictionary by Value in Python
September 23, 2022 - In this article, we'll explore how to sort a dictionary in Python by its value. These solutions use for loops and the sorted() function, as well as lambdas and the operator module.
🌐
Career Karma
careerkarma.com › blog › python › how to sort a dictionary by value in python
How to Sort a Dictionary by Value in Python | Career Karma
December 1, 2023 - Using the Python sorted() method, you can sort the contents of a dictionary by value. For instance, to rank the popularity of items on a coffee menu, or list those items in alphabetical order, you can use Python’s sorted() method.
🌐
Real Python
realpython.com › sort-python-dictionary
Sorting a Python Dictionary: Values, Keys, and More – Real Python
December 14, 2024 - Interactive Quiz Sorting a Python Dictionary: Values, Keys, and More · Sort Python dictionaries by keys or values using sorted(), lambdas, and itemgetter. Take this quiz to check your understanding.
🌐
AskPython
askpython.com › home › 3 ways to sort a dictionary by value in python
3 Ways to Sort a Dictionary by Value in Python - AskPython
August 6, 2022 - Python sorted() function can be used to sort a dictionary by value in Python by passing the values through dict.items() to the method. The dict.items() method fetches the keys/values from a dictionary.
🌐
Vultr
docs.vultr.com › python › examples › sort-a-dictionary-by-value
Python Program to Sort a Dictionary by Value | Vultr Docs
November 21, 2024 - The key function in sorted()—lambda x: x[1]—tells Python to sort the items by the second element of each tuple, which corresponds to the dictionary values.
🌐
Medium
medium.com › pythons-gurus › sorting-a-python-dictionary-by-value-8d405bef3439
Sorting Python Dictionary By Value | Python’s Gurus
July 11, 2024 - They’re ubiquitous in Python programming, used for everything from simple data storage to complex algorithm implementations. However, one limitation of dictionaries is that they don’t maintain any specific order of their elements. This can be problematic when we need to process dictionary items in a particular sequence, especially based on their values. In this comprehensive guide, we’ll explore various methods to sort a Python dictionary by its values.
🌐
GeeksforGeeks
geeksforgeeks.org › python › sort-python-dictionary-by-value
Sort Python Dictionary by Value - GeeksforGeeks
July 23, 2025 - Whether using for loops, the `sorted()` method, the `operator` module with `itemgetter()`, lambda functions, or creating a new dictionary with sorted values, Python offers flexibility in implementing this task. Each method has its own advantages, allowing developers to choose the approach that best suits their preferences and requirements for sorting dictionaries based on values.
🌐
Codecademy
codecademy.com › article › how-to-sort-a-dictionary-by-key-or-value-in-python
How to Sort a Dictionary by Key or Value in Python | Codecademy
The following example demonstrates how OrderedDict maintains the original insertion order of items with duplicate values: ... The student_scores dictionary is sorted by values in ascending order. Since both 'Charlie' and 'Brayne' have the same value (85), OrderedDict preserves their original insertion order. This ensures a stable and predictable result, even when values are duplicated. In this article, we explored how to sort Python dictionaries by keys—to organize entries alphabetically or numerically—and by values—to rank data based on importance or frequency.
🌐
Flexiple
flexiple.com › python › python-sort-dictionary-by-value
How to sort dictionary by value in Python? | Felxiple Tutorials | Python - Flexiple
March 23, 2022 - In the above example, we sort the dictionary using the sorted() function and create a new dictionary sortdict with the sorted values. The Python dictionary can also be sorted without converting the items to a list.
🌐
YouTube
youtube.com › watch
How To Sort A Dictionary By Value (Python Recipes) - YouTube
In this video I am going to be showing you how you can sort a dictionary by its value in Python.▶ Become job-ready with Python:https://www.indently.io▶ Follo...
Published   July 1, 2024
🌐
PythonHow
pythonhow.com › how › sort-a-list-of-dictionaries-by-a-value-of-the-dictionary
Here is how to sort a list of dictionaries by a value of the dictionary in Python
New: Practice Python, JavaScript ... print(sorted_list) ... To sort a list of dictionaries by a value of the dictionary in Python, you can use the sorted() function....
🌐
Python Pool
pythonpool.com › home › tutorials › sort a dictionary by value in python: sorted(), ties, and top values
Sort a Dictionary by Value in Python: sorted(), Ties, and Top Values
April 19, 2021 - Sort Python dictionaries by value with sorted(), lambda, itemgetter, reverse order, tie-breakers, and ordered output.