Dictionaries do not have any inherent order. Or, rather, their inherent order is "arbitrary but not random", so it doesn't do you any good.

In different terms, your d and your e would be exactly equivalent dictionaries.

What you can do here is to use an OrderedDict:

from collections import OrderedDict
d = { '123': { 'key1': 3, 'key2': 11, 'key3': 3 },
      '124': { 'key1': 6, 'key2': 56, 'key3': 6 },
      '125': { 'key1': 7, 'key2': 44, 'key3': 9 },
    }
d_ascending = OrderedDict(sorted(d.items(), key=lambda kv: kv[1]['key3']))
d_descending = OrderedDict(sorted(d.items(), 
                                  key=lambda kv: kv[1]['key3'], reverse=True))

The original d has some arbitrary order. d_ascending has the order you thought you had in your original d, but didn't. And d_descending has the order you want for your e.


If you don't really need to use e as a dictionary, but you just want to be able to iterate over the elements of d in a particular order, you can simplify this:

for key, value in sorted(d.items(), key=lambda kv: kv[1]['key3'], reverse=True):
    do_something_with(key, value)

If you want to maintain a dictionary in sorted order across any changes, instead of an OrderedDict, you want some kind of sorted dictionary. There are a number of options available that you can find on PyPI, some implemented on top of trees, others on top of an OrderedDict that re-sorts itself as necessary, etc.

Answer from abarnert on Stack Overflow
Top answer
1 of 13
87

Dictionaries do not have any inherent order. Or, rather, their inherent order is "arbitrary but not random", so it doesn't do you any good.

In different terms, your d and your e would be exactly equivalent dictionaries.

What you can do here is to use an OrderedDict:

from collections import OrderedDict
d = { '123': { 'key1': 3, 'key2': 11, 'key3': 3 },
      '124': { 'key1': 6, 'key2': 56, 'key3': 6 },
      '125': { 'key1': 7, 'key2': 44, 'key3': 9 },
    }
d_ascending = OrderedDict(sorted(d.items(), key=lambda kv: kv[1]['key3']))
d_descending = OrderedDict(sorted(d.items(), 
                                  key=lambda kv: kv[1]['key3'], reverse=True))

The original d has some arbitrary order. d_ascending has the order you thought you had in your original d, but didn't. And d_descending has the order you want for your e.


If you don't really need to use e as a dictionary, but you just want to be able to iterate over the elements of d in a particular order, you can simplify this:

for key, value in sorted(d.items(), key=lambda kv: kv[1]['key3'], reverse=True):
    do_something_with(key, value)

If you want to maintain a dictionary in sorted order across any changes, instead of an OrderedDict, you want some kind of sorted dictionary. There are a number of options available that you can find on PyPI, some implemented on top of trees, others on top of an OrderedDict that re-sorts itself as necessary, etc.

2 of 13
71

A short example to sort dictionary is desending order for Python3.

a1 = {'a':1, 'b':13, 'd':4, 'c':2, 'e':30}
a1_sorted_keys = sorted(a1, key=a1.get, reverse=True)
for r in a1_sorted_keys:
    print(r, a1[r])

Following will be the output

e 30
b 13
d 4
c 2
a 1
🌐
GeeksforGeeks
geeksforgeeks.org › python › sort-dictionary-by-value-python-descending
Sort Dictionary by Value Python Descending - GeeksforGeeks
July 23, 2025 - In this approach, we use the sorted() method and Lambda function to sort the input_dict by values in the descending (high to low) order and store the result in the new dictionary as output with the descending order sorted key-value pairs.
Discussions

How to Sort a Dict in Descending Order by Value With Python
There is a difference between sorting tuples of (value, key) and sorting on the value, namely if there are multiple subjects with the same grade. In the first case, they will be sorted by reverse alphabetical ordering (thus {"Math": 42, "Science": 42} will become {"Science": 42, "Math": 42}) while in the second case, they will keep the ordering they appeared in the original dictionary. This also matters if the key is an unorderable type: if they happen to be of a type where < is not defined on, the first method will raise an error. Also, this is a minor nitpick but it pains me to see dict((k, v) for v, k in sorted_value_key_pairs) rather than {k: v for v, k in sorted_value_key_pairs}. We've had dict comprehensions since 2.7 and 3.0, people! More on reddit.com
🌐 r/Python
7
4
April 14, 2021
How do I sort dictionary keys by their values?
Please don't shadow builtin names like dict with your variables. sorted takes a key function to determine what to sort on, and a reverse argument to sort in reverse order. >>> votes.items() [('jane', 3), ('john', 6), ('jack', 4), ('jill', 0), ('joe', 2)] >>> sorted(votes.items(), key=lambda pair: pair[1], reverse=True) [('john', 6), ('jack', 4), ('jane', 3), ('joe', 2), ('jill', 0)] There is also a standard factory in operator for item getter functions like that: >>> import operator >>> second = operator.itemgetter(1) >>> sorted(votes.items(), key=second, reverse=True) [('john', 6), ('jack', 4), ('jane', 3), ('joe', 2), ('jill', 0)] For this particular case, the standard collections.Counter is most suitable both for collecting votes and sorting them: >>> from collections import Counter >>> Counter(votes).most_common() [('john', 6), ('jack', 4), ('jane', 3), ('joe', 2), ('jill', 0)] >>> votes = Counter() >>> votes['john'] += 1 >>> votes['john'] += 1 >>> votes['jill'] += 1 >>> votes.most_common() [('john', 2), ('jill', 1)] More on reddit.com
🌐 r/learnpython
10
19
July 14, 2014
python - How do I sort a dictionary by value? - Stack Overflow
Note: I have read Stack Overflow ... by a value of the dictionary? and probably could change my code to have a list of dictionaries, but since I do not really need a list of dictionaries I wanted to know if there is a simpler solution to sort either in ascending or descending ... More on stackoverflow.com
🌐 stackoverflow.com
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
0
0
October 3, 2023
🌐
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
Python provides the built-in sorted() function to efficiently sort dictionaries. The sorted() function returns a new sorted list derived from the elements of any iterable. When applied to a dictionary’s items, it enables sorting by values in ascending or descending order.
🌐
Real Python
realpython.com › sort-python-dictionary
Sorting a Python Dictionary: Values, Keys, and More – Real Python
December 14, 2024 - To sort a dictionary by its values, use the sorted() function with the .items() method and specify a key parameter with a lambda function to extract the value. Can you sort a Python dictionary in descending order?Show/Hide
🌐
DataCamp
datacamp.com › tutorial › sort-a-dictionary-by-value-python
How to Sort a Dictionary by Values in Python | DataCamp
June 19, 2024 - The .sorted() function will sort the values alphabetically in ascending or descending order, just as it does with numbers. A2: To sort a dictionary with nested dictionaries, we need to define a custom sorting function that extracts and compares ...
🌐
w3resource
w3resource.com › python-exercises › dictionary › python-data-type-dictionary-exercise-1.php
Python: Sort (ascending and descending) a dictionary by value - w3resource
June 28, 2025 - # The result is a list of sorted ... sorted list of key-value pairs back into a dictionary. # The 'reverse=True' argument sorts the list in descending order by value....
Find elsewhere
🌐
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 - scores = {'Alice': 85, 'Bob': 92, 'Charlie': 78, 'Diana': 95} # Sort by value (descending) - highest first sorted_scores = dict(sorted(scores.items(), key=lambda x: x[1], reverse=True)) print(sorted_scores) # {'Diana': 95, 'Bob': 92, 'Alice': 85, 'Charlie': 78}
🌐
freeCodeCamp
freecodecamp.org › news › sort-dictionary-by-value-in-python
Sort Dictionary by Value in Python – How to Sort a Dict
September 13, 2022 - You can see the dictionary has been sorted by values in ascending order. You can also sort it in descending order.
🌐
Miguendes
miguendes.me › how-to-sort-a-dict-in-descending-order-by-value-with-python
Python: How to Sort a Dictionary by Value in Descending Order
February 20, 2021 - The quickest way is to iterate over the key-value pairs of your current dict and call sorted passing the dictionary values and setting reversed=True. If you are using Python 3.7, regular dicts are ordered by default.
🌐
Reddit
reddit.com › r/python › how to sort a dict in descending order by value with python
r/Python on Reddit: How to Sort a Dict in Descending Order by Value With Python
April 14, 2021 - grades = {"Math": 34, "Science": 12, "English": 89, "Physics": 8} grades {'Math': 34, 'Science': 12, 'English': 89, 'Physics': 8} value_key_pairs = ((value, key) for (key,value) in grades.items()) sorted_value_key_pairs = sorted(value_key_pairs, reverse=True) sorted_value_key_pairs [(89, 'English'), (34, 'Math'), (12, 'Science'), (8, 'Physics')] {k: v for v, k in sorted_value_key_pairs} {'English': 89, 'Math': 34, 'Science': 12, 'Physics': 8} ... I built a programming language interpreted in Python! ... Need help building function that will return dictionary key if inputted list matches dictionary value.
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › how to sort dictionary by value in python
How to Sort Dictionary by Value in Python - Spark By {Examples}
May 31, 2024 - How do I sort a dictionary by values in descending order? To sort a dictionary by its values in descending order, you can use the sorted() function along with a lambda function as the sorting key and setting the reverse parameter to True.
🌐
Reddit
reddit.com › r/learnpython › how do i sort dictionary keys by their values?
r/learnpython on Reddit: How do I sort dictionary keys by their values?
July 14, 2014 -

If I have a dictionary:

dict = {
        "john":6,
        "jill":0,
        "jack":4,
        "joe":2,
        "jane":3
        }

How would I sort the keys by their values, so I would end up with something like this?

print dict
{'john': 6, 'jack': 4, 'jane': 3, 'joe': 2, 'jill': 0}

I'm familiar with the sorted() method, but that only prints the keys and even then in the ascending order. While I can live with ascending order, descending would be much better - and I certainly need the values.

I'm making a program that calculates votes for people, so after sorting the keys I will then make a for loop which prints them into a more readable format, but I'm fairly certain I can do that part - just adding this info in case it's relevant.

Thanks!

Top answer
1 of 16
7095

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
1648

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.

🌐
GeeksforGeeks
geeksforgeeks.org › python › python-sort-python-dictionaries-by-key-or-value
Sort Python Dictionary by Key or Value - Python - GeeksforGeeks
Let's explore different methods to sort dictionary by key or value in Python. 1. Using sorted() with lambda: This method sorts the dictionary efficiently by its values using the sorted() function and a lambda expression.
Published   January 13, 2026
🌐
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
🌐
YoungWonks
youngwonks.com › blog › python-sort-dictionary-by-key-or-value
Python Sort Dictionary by Key or Value
April 10, 2023 - To sort a dictionary by its keys, we can simply use the sorted function and pass in the dictionary as the iterable. The sorted function can sort the keys in ascending or descending order and ...
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › python sort dictionary by key
Python Sort Dictionary by Key - Spark By {Examples}
May 31, 2024 - To sort the Python dictionary by key in descending order use the ‘reverse‘ param as ‘True‘ and then pass it into the sorted() function.
🌐
Arrowhitech
blog.arrowhitech.com › sort-a-dictionary-by-value-in-python-useful-guide-you-need-to-know
Sort a dictionary by value in Python: Useful guide you need to know – Blogs | AHT Tech | Digital Commerce Experience Company
Then, here is the program for sorting in descending order ... Let’s look into this code. The dictionary named “ order” holds the names of drinks as keys, and the number of orders as values. In this example, we use the sorted () method to sort the dictionary in descending order.
🌐
Medium
medium.com › pythons-gurus › sorting-a-python-dictionary-by-value-8d405bef3439
Sorting Python Dictionary By Value | Python’s Gurus
July 11, 2024 - The lambda function extracts the salary value (x[1]['salary']) from the dictionary value associated with each employee ID. The reverse=True argument ensures sorting in descending order (highest to lowest salary).