Python Bibliotheca
Python resources for teachers and students.

Sorting a list using a dictionary

Using a list of lists is a common way to store more complex data. There's no easy way, however, to sort and print the list of lists without using some extra code. For this example, we'll use a Python dictionary to store the key that will be used to sort the list. Here's the code:

import string

# Use a list of lists to hold the information
phoneList = [['Billy Bob Jones', '651-405-2345'],
             ['Xavier Brown', '763-506-6789'],
             ['Sue Smith', '612-789-0011']]
# Create a dictionary to allow for sorting
phoneDict = {}
for person in phoneList:
    names = string.split(person[0])
    lastName = names[-1]
    phoneDict[lastName] = person # Use last name as the dictionary key
# Sort the dictionary keys
nameKeys = phoneDict.keys()
nameKeys.sort()
# Now print the list sorted by last name
print "%-20s  Number" % 'Name'
print "="*34
for lastName in nameKeys:
    name = phoneDict[lastName][0]
    number = phoneDict[lastName][1]
    print "%-20s  %s" % (name, number)

When the program runs, the output looks like:

Name                  Number
==================================
Xavier Brown          763-506-6789
Billy Bob Jones       651-405-2345
Sue Smith             612-789-0011

The only function of the dictionary in this example is to associate the sorting key with the rest of the data in the list. You can specify a different sorting key in your program easily.

[ Copyright 2005, Tim Wilson ]

Comments, questions, or suggestions? Email the webmaster