How to Sort a Dictionary in Python by the Values
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.
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:
shoppingList = {'milk':2.19, 'bread':3.09, 'coffee':4.59, 'eggs':1.79, 'cheese':4.99}
-
4
Print out the dictionary sorted by value. To sort by value, you need to use the sorted() function and "itemgetter," like this:
print(sorted(shoppingList.items(), key=itemgetter(1)))
-
5
Press F5 to run the program. The program outputs the dictionary sorted by value, and that output looks like this:
[('eggs', 1.79), ('milk', 2.19), ('bread', 3.09), ('coffee', 4.59), ('cheese', 4.99)]
-
1