How To Sort A Dictionary By Key In Python – Definitive Guide

Python dictionaries allow you to store key-value pairs.

You can sort a dictionary by key using the sorted(yourdict.items()) method.

This tutorial teaches you how to sort a dictionary by key in Python using different methods.

If You’re in Hurry…

If you want to sort a dictionary by key and create a new dictionary out of it, you can use the below snippet.

This is applicable when you use Python version 3.6 or a later version.

yourdict = {
    "one": 1,
    "two": 2,
    "three": 3,
    "four": 4,
}

sorted_dict= dict(sorted(yourdict.items()))

sorted_dict

Output

    {'four': 4, 'one': 1, 'three': 3, 'two': 2}

If you want to iterate over the dictionary using its key in a sorted way, you can use the below method.

yourdict = {
    "one": 1,
    "two": 2,
    "three": 3,
    "four": 4,
}

for key, val in sorted(yourdict.items()):
    print(key, val)

Output

    four 4
    one 1
    three 3
    two 2

If You Want to Understand Details, Read on…

Different methods are available to sort the dictionary keys.

Python dictionaries are unordered until Python version 3.6. The order will not be maintained with the earlier Python versions even if you sort the keys and create a dictionary. Hence, you need to sort it while iterating over it.

Using Sorted Method

This section teaches you how to use the sorted function to sort the dictionary keys. The sorted function returns a sorted list of items available in the iterable. The iterable can be lists, tuples, sets or a list of dictionary keys or items.

To Create a New Ordered Dictionary

You can use the below code to create a dictionary with the sorted keys.

  • Sort the dictionary keys using sorted(yourdict.items())
  • Pass it to the dict() constructor. It creates a new dictionary with the keys in the sorted order

When to use

You can use this method when using a Python version greater than 3.6 because dictionary key insertion orders are preserved only from this version. If you use this in the earlier version, then it doesn’t keep the sort order after creating the dictionary.

Code

yourdict = {
    "one": 1,
    "two": 2,
    "three": 3,
    "four": 4,
}

sorted_dict= dict(sorted(yourdict.items()))

sorted_dict

Output

The dictionary keys are sorted, a new dictionary is created out of it, and the sort order is maintained in the dictionary.

    {'four': 4, 'one': 1, 'three': 3, 'two': 2}

To Just Iterate Over Dictionary In a Sorted Way

If you want to iterate over the dictionary in a sorted way, then you can use the below code snippet.

It iterates the dictionary items() in a sorted way and iterates over it using the for loop.

Code

yourdict = {
    "one": 1,
    "two": 2,
    "three": 3,
    "four": 4,
}

for key, val in sorted(yourdict.items()):
    print(key, val)

Output

The dictionary keys are sorted, iterated over the for loop, and the key values are printed.

    four 4
    one 1
    three 3
    two 2

Using Sorted With Reverse Keyword

This section teaches you how to use the reverse parameter in the sorted() function.

This parameter is useful when you want to sort the list of items in reverse chronological order.

To create a new ordered dictionary

If you want to create a new dictionary after sorting the existing dictionary keys in a reversed order, then you can use the below code.

This also works only after Python version 3.6.

  • It sorts the dictionary keys in a reversed order
  • The list is passed to the dictionary constructor, and a new dictionary is created

Code

yourdict = {
    "one": 1,
    "two": 2,
    "three": 3,
    "four": 4,
}

sorted_dict= dict(sorted(yourdict.items(), reverse=True))

sorted_dict

Output

    {'two': 2, 'three': 3, 'one': 1, 'four': 4}

To Iterate Over A Dictionary In A Reversed Order

You can use the code below if you want to iterate over the dictionary in a reversed sort order.

yourdict = {
    "one": 1,
    "two": 2,
    "three": 3,
    "four": 4,
}

for key, val in sorted(yourdict.items(), reverse=True):
    print(key, val)

Output

The dictionary keys are sorted in a reversed order and iterated over it.

    two 2
    three 3
    one 1
    four 4

Using OrderedDict

Python dictionaries are unordered until Python Version 3.6. So if you’re using the older versions, you need to use the orderedDict from collections to maintain the sorted key orders.

The orderedDict has been available since Python version 2.8.

To create an orderedDict after sorting the dictionary based on keys, use the below code snippet.

  • Dictionary keys are sorted using the sorted() function
  • Sorted items are passed to the OrderedDict constructor. It creates an ordered dictionary

Code

from collections import OrderedDict 

yourdict = {
    "one": 1,
    "two": 2,
    "three": 3,
    "four": 4,
}

ordered_dict = OrderedDict(sorted(yourdict.items()))

ordered_dict

Output

    OrderedDict([('four', 4), ('one', 1), ('three', 3), ('two', 2)])

This is how you can sort the dictionary using its keys and create a new dictionary in Python versions earlier than version 3.6.

Sort Dictionary With Key in Ascending Order

To sort a dictionary with keys in ascending order, you can use the sorted() function.

Sorted() function sorts in ascending order by default.

Code

yourdict = {
   1: "one",
   9: "nine", 
   2: "two",
   3: "three",
   4: "four"
}

for key, val in sorted(yourdict.items()):
    print(key, val)

Output

    1 one
    2 two
    3 three
    4 four
    9 nine

Sort Dictionary With Key in Descending Order

To sort a dictionary with keys in descending order, you can use the sorted() function with the reverse=True parameter.

Code

yourdict = {
   1: "one",
   9: "nine", 
   2: "two",
   3: "three",
   4: "four"
}

for key, val in sorted(yourdict.items(), reverse=True):
    print(key, val)

Output

    9 nine
    4 four
    3 three
    2 two
    1 one

Sort Dictionary Keys Alphabetically

When dictionary keys are alphabets, you can sort the keys alphabetically using the sorted() function.

Code

yourdict = {
    "one": 1,
    "two": 2,
    "three": 3,
    "four": 4,
}

for key, val in sorted(yourdict.items()):
    print(key, val)

Output

    four 4
    one 1
    three 3
    two 2

Sort Dictionary With Key in Reverse

This section teaches you how to reverse the existing key order using the reversed() function.

The reversed() function returns the reversed iterator. You can use the for loop to iterate over it.

The keys are not sorted in any way. The existing order is just reversed.

Code

yourdict = {
   1: "one",
   9: "nine", 
   2: "two",
   3: "three",
   4: "four"
}

for key, val in reversed(yourdict.items()):
    print(key, val)

Output

The dictionary keys are iterated in a reverse way of the existing order.

    4 four
    3 three
    2 two
    9 nine
    1 one

This is how you can reversed() function to sort a dictionary key in a reversed order.

Conclusion

You’ve learned how to sort a dictionary by key in Python 3.6 and on the older versions. Additionally, you’ve created a dictionary after sorting the keys and created an orderedDict to preserve the order while using the Python versions older than 3.6.

You’ve also learned how to sort keys in chronological order and reverse chronological order.

You May Also Like

Leave a Comment