How to Sort a Dictionary in Python by the Values

Written by mike wallace

Share

Tweet

Share

Email

The Python programming language has several different ways of storing data. The dictionary is one way Python can store data. A dictionary stores data as key-value pairs, just like a real dictionary stores data as word-definition pairs. Dictionaries can be sorted by either the key or the value. The syntax for sorting a dictionary is straightforward, and even total beginners to Python can pick it up quickly.

Skill level:

Moderately Easy

Other People Are Reading

Things you need

Instructions

1

Open the IDLE text editor that comes with the Python download. Find the IDLE text editor in Program Files (or Applications for Macintosh), in the Python directory. A blank source code file opens in the IDLE text editor window.

2

Import "itemgetter" from the module "operator." Write the following at the top of the source code file to import this method:

from operator import itemgetter

3

Declare a dictionary and fill it with values. You can write something like this: