Learn to Program using Python

Valid Keys, Key Lists, Iteration

By Richard G. Baldwin

Python Programming Lesson #68

December 15,2000


Preface

This document is part of a series of online tutorial lessons designed to teach you how to program using the Python scripting language.  After we cover regular Python, the lessons will cover JPython.  This will form a link between Python and Java.

Viewing tip

You may find it useful to open another copy of this lesson in a separate browser window.  That will make it easier for you to scroll back and forth among the different listings, without losing your place, while you are reading about them.

Something for everyone

Beginners start at the beginning, and experienced programmers jump in further along. Lesson 1, Getting Started provides an overall description of this online programming course.  (You will find a consolidated index to all of my Python, Java, and XML tutorials, including Lesson 1 mentioned above, on my website.)

Introduction

A previous lesson entitled Getting Started with Dictionaries introduced you to the characteristics of the Python dictionary, and showed you how to use the basic characteristics.

Preview

This lesson will teach you about valid keys, key lists, and iteration on key lists.

What Is a Dictionary?

The following is a general summary of the characteristics of a Python dictionary: Will illustrate these characteristics

Some of these characteristics were illustrated in a previous lesson entitled Getting Started with Dictionaries.  Other characteristics will be illustrated using sample programs in this and subsequent lessons.

Sample Program

Listing 11, near the end of the lesson, shows a Python script that: I will break this program down and discuss it in fragments.

Use of boldface

I typically use boldface for emphasis in these lessons, although Python code is not written using boldface.

The initialized  dictionary

The boldface statement in Listing 1 creates a new dictionary and initializes it to contain one key:value pair.  The key is 5 and the value is "number".
 
# File Dict04.py
# Rev 08/06/00
# Copyright 2000, R. G. Baldwin
# Illustrates 
#  Valid keys
#  keys() method
#  Iteration on a list of keys
#-------------------------------
# Create initialized dictionary
d1 = {5:"number"}

# Display it
print d1,'\n'

Listing 1

The remaining code in Listing 1 displays the dictionary.

The output produced by this code fragment is shown in Listing 2.
 
{5: 'number'}

Listing 2

As you can see from the boldface line in Listing 2, the dictionary is displayed as a pair of curly braces containing the key:value pair discussed above.

Adding key:value pairs

The first two statements in Listing 3 use indexing by key value and assignment to add two new key:value pairs to the dictionary.
 
# Add items
d1["to"] = "string"
d1[(1,"a",("b","c"))] = "tuple"
# Display it
print d1,'\n'

Listing 3

Have we seen this before?

We saw something like this in a program in the earlier lesson entitled Getting Started with Dictionaries.  However, that lesson used string objects for keys.

Using a tuple as a key

In this program, I used a string for one key and I used a tuple for the other key, as shown by the highlighted material in Listing 3.  (Note that the tuple used as a key contains a nested tuple.)

Is a tuple a valid key?

Recall that you can use any immutable object as a key.

When the key is a tuple, the contents of the tuple must themselves be immutable.

That requirement is satisfied here because the contents of the tuple (and its nested tuple) are numbers and strings.

Values can be any type

In this case, both values of the key:value pair are strings.  However, they could be any type.

Display the modified dictionary

After adding the two new key:value pairs to the dictionary, the remaining code in Listing 3 displays the modified dictionary.

The output produced by this code fragment is shown in Listing 4.
 
{(1, 'a', ('b', 'c')): 'tuple',
 'to': 'string',
 5: 'number'}

Listing 4
(Line beaks entered manually.)

Manually entered line breaks and color

Note that I manually entered line breaks to force the dictionary to fit in the available display space for this lesson.  I also colored the keys red and the values blue to make them easier to separate visually.

Order is randomized

As shown in Listing 4, the dictionary now contains the original key:value pair, plus the two new key:value pairs that I added.

Note that the items do not appear in the same order that I added them.  As mentioned in the earlier lesson entitled Getting Started with Dictionaries, items are purposely stored in a dictionary in a random order.

Getting a list of keys

The boldface code in Listing 5 invokes the keys() method on the dictionary object to get a list of the keys currently stored in the dictionary.
 
# Get and display keys
L1 = d1.keys()
print "The keys are:"
print L1,'\n'

Listing 5

This list of keys is then displayed as shown in Listing 6.
 
The keys are:
[(1, 'a', ('b', 'c')), 'to', 5]

Listing 6

This is an ordinary list, consisting of a sequence of items in square brackets, separated by commas.  (I discussed lists in an earlier lesson entitled Lists, Part I.)

Color was added for this display

Note that I color-coded the items in the key list using alternating colors of red and blue to make them easier to separate visually.

The first key is a tuple, the second key is a string, and the third key as a number.

No surprise here

This should come as no surprise, because these are the same keys that were created earlier for the three key:value pairs.  This is simply a different view of the keys.

Useful for iteration

However, as we will see shortly, this view of the keys is very useful for iterating on the keys in the dictionary.

Iterate on the key list

The boldface code in Listing 7 uses a for loop to iterate on the key list to display each key:value pair in a tabular format.
 
# Iterate on the key list
# Print dictionary and length
print "Dictionary contents"
for x in L1: 
  print x,'\t',d1[x]
print "Length = ",len(d1),'\n'

Listing 7

According to the Python Tutorial, "Python's for statement iterates over the items of any sequence (e.g., a list or a string), in the order that they appear in the sequence."

What does this really mean?

I will have quite a lot more to say about the Python for loop in a subsequent lesson.  For now, you can interpret the operation of the boldface code in Listing 7 as follows:

Then get and print the length

After each of the key:value pairs have been printed in the tabular format described above, the code in Listing 7 gets and prints the length of the dictionary using the len() method discussed in earlier lessons.

The output

Listing 8 shows the output produced by the code in Listing 7.
 
Dictionary contents
(1, 'a', ('b', 'c'))    tuple
to      string
5       number
Length =  3

Listing 8

In Listing 8, the keys were colored red and the values were colored blue to make it easier to separate them visually.

Not too pretty but...

Although the length of the first key is so long that it disrupts the column structure in the tabular format, you can see how the items in the key list were used in an iterative manner to fetch and display each key along with its associated value.

Although it should come as no surprise to you at this point, Listing 8 also shows the length of the dictionary to be three items.

A list is not a valid key

A list is a mutable object.  Therefore, it cannot be used as a key in a dictionary.

The code in Listing 9 demonstrates the truth of the previous statement.
 
# A list is not a valid key
print "Try to index with a list"
d1[ [8,9,10] ] = "not allowed"

Listing 9

This code attempts to index the dictionary object using a list as a key to add a new item to the dictionary.

The output from the code in Listing 9 is shown in Listing 10.
 
Try to index with a list
Traceback (innermost last):
  File "Dict04.py", line 33, in ?
    d1[ [8,9,10] ] = "not allowed"
TypeError: unhashable type

Listing 10

As you can see, the program terminated at this point with an error message telling us that the list is an unhashable type.

Summary

This lesson has taught you about valid keys, key lists, and iteration on key lists.

What's Next?

Upcoming lessons will contain sample programs that illustrate a number of characteristics of dictionaries, including the following:

Review

1.  Write Python code that will create, initialize, and display a dictionary.  The dictionary should have keys of type string and number, and should have values of type list and tuple.

Ans:  See Listing 12.
 
# File Dict10.py
# Rev 08/08/00
# Copyright 2000, R. G. Baldwin
# Illustrates initializing a 
#  dictionary
#-------------------------------
d1 = {5:[6,7,8],"a":(1,2,3)}
print d1

Listing 12

2.  Write Python code that gets and displays a list of the keys contained in a dictionary.

Ans:  See Listing 13.
 
# File Dict12.py
# Rev 08/08/00
# Copyright 2000, R. G. Baldwin
# Illustrates getting a list of
#  keys
#-------------------------------
d1 = {5:[6,7,8],"a":(1,2,3)}
print d1.keys()

Listing 13

3.  Write Python code that will iterate on a key list to produce a display of the keys and their associated values.  Each key:value pair should appear on a new line, and the value should be separated from the key using a colon.

Ans:  See Listing 14.
 
# File Dict14.py
# Rev 08/06/00
# Copyright 2000, R. G. Baldwin
# Illustrates iterating on a key
#  list from a dictionary
#-------------------------------
# Create initialized dictionary
d1 = {5:"number",\
      "a":"string",\
      (1,2):"tuple"}

# Iterate on a key list
print "Dictionary contents"
for x in d1.keys(): 
  print x,':',d1[x]

Listing 14

4..  True or false?  A list can be used as a key in a dictionary.

Ans:  False.  Only immutable types can be used as keys in a dictionary.  A list is a mutable type.

Listing of Sample Program

A complete listing of the program is shown in Listing 11.
 
# File Dict04.py
# Rev 08/06/00
# Copyright 2000, R. G. Baldwin
# Illustrates 
#  Valid keys
#  keys() method
#  Iteration on a list of keys
#-------------------------------
# Create initialized dictionary
d1 = {5:"number"}
# Display it
print d1,'\n'

# Add items
d1["to"] = "string"
d1[(1,"a",("b","c"))] = "tuple"
# Display it
print d1,'\n'

# Get and display keys
L1 = d1.keys()
print "The keys are:"
print L1,'\n'

# Iterate on the key list
# Print dictionary and length
print "Dictionary contents"
for x in L1: 
  print x,'\t',d1[x]
print "Length = ",len(d1),'\n'

# A list is not a valid key
print "Try to index with a list"
d1[ [8,9,10] ] = "not allowed"

Listing 11



Copyright 2000, Richard G. Baldwin.  Reproduction in whole or in part in any form or medium without express written permission from Richard Baldwin is prohibited.

About the author

Richard Baldwin is a college professor and private consultant whose primary focus is a combination of Java and XML. In addition to the many platform-independent benefits of Java applications, he believes that a combination of Java and XML will become the primary driving force in the delivery of structured information on the Web.

Richard has participated in numerous consulting projects involving Java, XML, or a combination of the two.  He frequently provides onsite Java and/or XML training at the high-tech companies located in and around Austin, Texas.  He is the author of Baldwin's Java Programming Tutorials, which has gained a worldwide following among experienced and aspiring Java programmers. He has also published articles on Java Programming in Java Pro magazine.

Richard holds an MSEE degree from Southern Methodist University and has many years of experience in the application of computer technology to real-world problems.

baldwin.richard@iname.com

-end-