Print a dictionary sorted by Key in Python

avatar

Borislav Hadzhiev

Last updated: Sep 15, 2022

banner

Photo from Unsplash

Print a dictionary sorted by Key in Python #

Use the pprint() method to print a dictionary sorted by key, e.g. pprint(my_dict). The pprint() method sorts the keys in the dictionary alphabetically and prints the result.

main.py
from pprint import pprint my_dict = { 'bobbyhadz': 1, 'alice': 5, 'carl': 3, } pprint(my_dict) # 👉️ {'alice': 5, 'bobbyhadz': 1, 'carl': 3} # {'alice': 5, # 'bobbyhadz': 1, # 'carl': 3} pprint(my_dict, width=1) sorted_by_key = dict(sorted(my_dict.items())) print(sorted_by_key) # 👉️ {'alice': 5, 'bobbyhadz': 1, 'carl': 3} sorted_by_value = dict(sorted(my_dict.items(), key=lambda item: item[1])) print(sorted_by_value) # 👉️ {'bobbyhadz': 1, 'carl': 3, 'alice': 5}

The first example uses the pprint() method to pretty print a dictionary sorted by key.

The pprint.pprint method prints the formatted representation of an object.

We set the width argument to 1 to set the desired maximum number of characters per line to 1.
main.py
from pprint import pprint my_dict = { 'bobbyhadz': 1, 'alice': 5, 'carl': 3, } pprint(my_dict) # 👉️ {'alice': 5, 'bobbyhadz': 1, 'carl': 3} # {'alice': 5, # 'bobbyhadz': 1, # 'carl': 3} pprint(my_dict, width=1)

By default, the pprint() method sorts the keys in the dictionary alphabetically.

Whether the keys in the dictionary are sorted when printing is determined by the sort_dicts argument.

main.py
from pprint import pprint my_dict = { 'bobbyhadz': 1, 'alice': 5, 'carl': 3, } # ✅ sort_dicts is True by default pprint(my_dict) # 👉️ {'alice': 5, 'bobbyhadz': 1, 'carl': 3} pprint(my_dict, sort_dicts=False) # 👉️ {'bobbyhadz': 1, 'alice': 5, 'carl': 3}

When sort_dicts is set to False, the dictionary's items are printed in insertion order.

Alternatively, you can use the sorted() function and the dict() class.

main.py
my_dict = { 'bobbyhadz': 1, 'alice': 5, 'carl': 3, } sorted_by_key = dict(sorted(my_dict.items())) print(sorted_by_key) # 👉️ {'alice': 5, 'bobbyhadz': 1, 'carl': 3} sorted_by_value = dict(sorted(my_dict.items(), key=lambda item: item[1])) print(sorted_by_value) # 👉️ {'bobbyhadz': 1, 'carl': 3, 'alice': 5}

The dict.items method returns a new view of the dictionary's items ((key, value) pairs).

main.py
my_dict = { 'bobbyhadz': 1, 'alice': 5, 'carl': 3, } # 👇️ dict_items([('bobbyhadz', 1), ('alice', 5), ('carl', 3)]) print(my_dict.items())

We used the sorted() function to sort the keys.

main.py
my_dict = { 'bobbyhadz': 1, 'alice': 5, 'carl': 3, } # 👇️ [('alice', 5), ('bobbyhadz', 1), ('carl', 3)] print(sorted(my_dict.items())) sorted_by_key = dict(sorted(my_dict.items())) print(sorted_by_key) # 👉️ {'alice': 5, 'bobbyhadz': 1, 'carl': 3}

The last step is to pass the list of sorted key-value pair tuples to the dict() class.

Alternatively, you can use the json.dumps() method.

Print a dictionary sorted by Key using json.dumps() #

Use the json.dumps() method to print a dictionary sorted by key, e.g. print(json.dumps(my_dict, indent=4, sort_keys=True)). When the sort_keys argument is set to True, the keys of the dictionary are sorted alphabetically.

main.py
import json my_dict = { 'bobbyhadz': 1, 'alice': 5, 'carl': 3, } result = json.dumps(my_dict, indent=4, sort_keys=True) # { # "alice": 5, # "bobbyhadz": 1, # "carl": 3 # } print(result)

The json.dumps method converts a Python object to a JSON formatted string.

If indent is set to a non-negative integer, the JSON array elements or object members get pretty-printed with the specified indent level.

We used an indent level of 4 spaces, but you can use any other positive integer.

You can set the sort_keys argument to True to sort the keys of the dictionary when serializing to JSON.

Note that the json.dumps() method can only be used with dictionaries that contain values that can be serialized to JSON.

By default, the JSONEncoder class can convert the following objects and types to JSON.

PythonJSON
dictobject
list, tuplearray
strstring
int, float, int and float derived Enumsnumber
Truetrue
Falsefalse
Nonenull

If the dictionary contains values of any other type, it can't be directly passed to the json.dumps() method.

You can also use a for loop and a formatted string literal to print a dictionary sorted by key.

main.py
my_dict = { 'bobbyhadz': 1, 'alice': 5, 'carl': 3, } for key, value in sorted(my_dict.items()): # alice: 5 # bobbyhadz: 1 # carl: 3 print(f'{key}: {value}')

The first example uses a for loop and a formatted string literal to print the items in a dictionary sorted by key.

Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f.
main.py
var1 = 'bobby' var2 = 'hadz' result = f'{var1}{var2}' print(result) # 👉️ bobbyhadz

Make sure to wrap expressions in curly braces - {expression}.

You can also use the str.join() method to achieve the same result.

main.py
my_dict = { 'bobbyhadz': 1, 'alice': 5, 'carl': 3, } result = '\n'.join( f'{key}: {value}' for key, value in sorted(my_dict.items()) ) # alice: 5 # bobbyhadz: 1 # carl: 3 print(result)

We used the str.join() method to join the sorted items into a string with a newline (\n) character separator.

The str.join method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.

The string the method is called on is used as the separator between the elements.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.