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.

Basic Example

This is applicable when you use Python version 3.6 or a later version. Read below for other versions.

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

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

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

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

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 Iterate Over Dictionary In a Sorted Way

To iterate over the dictionary in a sorted way

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.

The reverse parameter is useful for sorting the list of items in reverse chronological order.

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}

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

  • Sorted the dictionary keys using the sorted() function
  • Pass the sorted items 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,

  • 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,

  • 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,

  • 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.
  • 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.

Additional Resources

Leave a Comment