Sort Dictionary by key in Python

Python dictionary is a useful data structure for maintaining a record of key and value pairs. In addition, the dictionary retains the order in which items were inserted from version 3.6 and allowed constant time for data retrieval. However, it doesn’t support indexing. This article will discuss how to sort a dictionary by key in Python. Let’s look at the dictionary data structure in Python.

What is a dictionary key?

The Dictionary data structure contains data in the form of key-value pairs. To clarify, imagine you have a book. In that case, that book must have a title and an author. Suppose the title is the key, and the author is the value. For instance:

book = {"The Godfather": "Mario Puzo", "Catch-22": "Joseph Heller"}
print(book["The Godfather"])
print(book["Mario Puzo"])

By using the book title key, we can get the value of the value, here, the author’s name. However, the opposite will not happen as there is no key with the author’s name.

The book's title returns the author's name
The book’s title returns the author’s name.
names = {'lil slugger':4, 'marumi':3, 'tuskiko':2,'mitsushiro':1}
names['Masami'] = 6
names['Taeko'] = 5
print(names)
A dictionary of names with a name as key and a number as its value.
A dictionary of names with a name as key and a number as its value.

The above example has printed a dictionary with a name as a key and an integer as a value. However, the objective is to sort a dictionary by key in Python.

Sort Dictionary by key in Python

Let’s look at various ways to sort a dictionary by key in Python. For example:

Using the sorted method

names_tup = sorted(names.items())
print(names_tup)
sorted_names = {k:v for k,v in names_tup}
print(f'Sorted dictionary: {sorted_names}')
List of tuples of key-value pairs
List of tuples of key-value pairs
names dictionary in sorted order alphabetically
names dictionary in sorted order alphabetically

Let’s go through the working of the above code:

  • We are using the sorted function on the names dictionary. It returns a list of tuples having keys and values stored.
  • Variable named names_tup stores the list of tuples sorted alphabetically.
  • Then, using dictionary comprehension, we loop over names_tup and store them in a dictionary named sorted_names.

Note: Instead of storing the sorted dictionary in another variable, you can also store it in the original variable if not in use.

Sort dictionary by key in Python, descending

The sorted function provides an additional parameter, namely reverse. The reverse parameter takes in a boolean value. If false(default value), sorts the iterable in ascending or regular order. However, when true, it sorts the iterable in descending order or reverses.

names_tup = sorted(names.items(), reverse = True)
sorted_names = {k:v for k,v in names_tup}
print(f'Reverse sorted dictionary: {sorted_names}')
Reverse sorted dictionary
Reverse sorted dictionary

Using lambda function

Using the lambda function, we can specify whether we want to sort a dictionary using keys or values. For instance:

names = {'key 1':'lil slugger', 'key 5':'marumi', 'key 2':'tuskiko','key 4':'mitsushiro'}
names['key 6'] = 'Masami'
names['key 5'] = 'Taeko'

names_sort_key = dict(sorted(names.items(), key=lambda item:item[0]))
print(names_sort_key)

The key parameter of the sorted function takes in a function. In the above code, we have added a lambda function to the key parameter of the sorted function. The item[0] indicates the dictionary’s key on which the dictionary is sorted.

Using the lambda function to sort the dictionary
Using the lambda function to sort the dictionary

Recommended reading | How to Sort a Dictionary by Value in Python

Using itemgetter of the operator module

Itemgetter is a part of the operator module of Python, which is a built-in library. Instead of the lambda function, itemgetter can be used to get a sorted dictionary over a key. Let’s take an example to elaborate our point:

from operator import itemgetter

players = [{'name':'Novak Djokovic', 'rank':1},
        {'name':'Daniil Medvedev', 'rank':2},
        {'name':'Alexander Zverev', 'rank':4},
        {'name':'Matteo Berrettini', 'rank':6},
        {'name':'Rafael Nadal', 'rank':3},
        {'name':'Stefanos Tsitsipas', 'rank':5}]

# ranked on basis of names
players_names = sorted(players, key=itemgetter('name'))
# ranked on world ranking
players_rank = sorted(players, key=itemgetter('name'))

print(players_names)
print("\n")
print(players_rank)

In the above code, we have taken the top 6 tennis players of the word and stored them in a dictionary with names and ranks as the keys. Additionally, the player’s list contains dictionaries.

  • Firstly, instead of the lambda function, we have used the itemgetter method of the operator’s library.
  • In the sorted function, we pass the list of dictionaries, and for the key parameter, we use the itemgetter method.
  • Players dictionary is sorted over a key that gets passed into the itemgetter method. For instance, the name and the rank in the above code.

Note: The Itemgetter method has an overall different internal implementation. Asz a result, making it faster. Moreover, it is more concise and readable than the lambda function.

Sorting dictionary using itemgetter method
Sorting dictionary using itemgetter method

Using the sorted and zip method

Let’s see how we can sort a dictionary over a key using the zip method.

names = {'key 1':'lil slugger', 'key 5':'marumi', 'key 2':'tuskiko','key 4':'mitsushiro'}
names['key 6'] = 'Masami'
names['key 5'] = 'Taeko'

sorted_names = dict(sorted(zip(names.keys(),names.values())))
print(sorted_names)

The sorted() function sorts the dictionary keys and values individually. Then, the zip method makes an iterator that aggregates or joins elements from each iterable.

Sorting dictionary using a zip method
I am sorting dictionaries using a zip method.

Using JSON

JSON or JavaScript Object Notation is a lightweight data-interchange format. It is easy for humans to read and write.

For instance, let’s look at the following code using which we can sort a dictionary.

import json

names = {'key 1':'lil slugger', 'key 5':'marumi', 'key 2':'tuskiko','key 4':'mitsushiro'}
names['key 6'] = 'Masami'
names['key 5'] = 'Taeko'

print(json.dumps(names,sort_keys=True))
Using json to sort keys of a dictionary
Using JSON to sort keys of a dictionary

Using the collection module OrderedDict

OrderedDict, a dictionary subclass, was introduced in Python’s version 3.1 to the standard library. It is a part of Python’s collection module. Read more here.

from collections import OrderedDict

names = {'key 1':'lil slugger', 'key 5':'marumi', 'key 2':'tuskiko','key 4':'mitsushiro'}
names['key 6'] = 'Masami'
names['key 5'] = 'Taeko'

names_od = OrderedDict(sorted(names.items()))
print(names_od)
Using OrderedDict to sort Dictionary by key Python
Using OrderedDict to sort a dictionary by key Python

Sort dictionary by key python date

from datetime import datetime

dates = {
    "04-01-2022": "Random text",
    "26-10-2022": "More random text",
    "31-07-2022": "Some more random text",
}

dates_ordered = dict(sorted(dates.items(), key=lambda x: datetime.strptime(x[0], "%d-%m-%Y")))
print(dates_ordered)
  • The striptime method of datetime converts date stored in string into a datetime object of format %d-%m-%Y. Where %d, %m, and %Y represent the date of the month, month number, and the year respectively.
  • Moreover, it is required because strings are ordered alphabetically. However, we want to sort the dictionary using date.
Dictionary sorted according to key(here date)
Dictionary sorted according to the key(here date)

Sort nested dictionary by key Python

books = {
    "The Godfather": {"author": "Mario Puzo", "release_yr": 1969},
    "Catch-22": {"author": "Joseph Heller", "release_yr": 1961},
    "The Lighthouse": {"author": "Virginia Woolf", "release_yr": 1927},
    "The Fault in Our Stars": {"author": "John Green", "release_yr": 2012},
}

books_sorted = dict(sorted(books.items(), key=lambda x: x[1]["release_yr"]))
print(books_sorted)

In the code above, we have a nested dictionary named books, containing the book’s name, author’s name, and their release years. After that, using the sorted and lambda function, with release_yr as a key, over which the dictionary is ordered. As a result, books are sorted in ascending order of their release years.

The nested dictionary books sorted based on release year
The nested dictionary books are sorted based on release year

FAQs on Sort Dictionary by Key in Python

Can we sort the dictionary keeping its data type the same?

You can sort a dictionary by keeping its data type the same using the sorted function.

Why is it not recommended to rely on dictionary sort/order?

Dictionary before python version 3.6 was not ordered. However, you can expect the items to maintain the order in which they were inserted.

Is sorted included by default?

Yes, sorted is already included function in Python3.

Conclusion

In the following article, we covered the various ways in which we can sort a dictionary. For instance, sorted and lambda functions, itemgetter, zip, etc. These methods can come in handy when you want to order your dictionary items.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments