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

  • Computer with Python 3.2 programming language installed (see Resource)

Show MoreHide

Instructions

  1. 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. 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. 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. 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. 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)]

Don't Miss

Resources

Filter:
  • All types
  • Articles
  • Slideshows
  • Videos
Sort:
  • Most relevant
  • Most popular
  • Most recent

No articles available

No slideshows available

No videos available

By using the eHow.co.uk site, you consent to the use of cookies. For more information, please see our Cookie policy.