Learn to Program using Python:  Using Tuples as Keys

Continuing the series on dictionaries, this lesson will teach you about modifying values and using tuples as keys.

Published:  January 2, 2001
By Richard G. Baldwin

Python Programming Lesson #72


Preface

This document is part of a series of online tutorial lessons designed to teach you how to program using the Python scripting language.

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 while you are reading about them.

Something for everyone

Beginners start at the beginning, and experienced programmers jump in further along.  The first lesson entitled Learn to Program using Python: Lesson 1, Getting Started, provides an overall description of this online programming course.

As of the date of this writing, EarthWeb doesn't maintain a consolidated index of my Python tutorial lessons, and sometimes my lessons are difficult to locate on the EarthWeb site.  You will find a consolidated index of my tutorial lessons at my web site.

Introduction

A previous lesson entitled Learn to Program using Python: Getting Started with Dictionaries, introduced you to the characteristics of the Python dictionary, and showed you how to use the basic characteristics.  This lesson will teach you about using tuples as keys in a Python dictionary.

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 previous lessons.  Other characteristics will be illustrated using the sample programs in this and subsequent lessons.

Sample Program

Listing 9 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

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

The initialized  dictionary

The boldface statement near the top of Listing 1 below creates a new dictionary and initializes it to contain two key:value pairs.  For the first element, the key is 5 and the value is the string "number".  For the second element, the key is "to" and the value is the string "string". (These two keys satisfy the requirement that the keys in a dictionary must be immutable.  Numbers and strings are immutable in Python.)
 
# Create initialized dictionary
d1 = {5:"number","to":"string"}
print "Dictionary contents"
print "Key",' : ',"Value"
for x in d1.keys():print x,' : ',d1[x]

print ""# Print blank line

Listing 1

Display the dictionary contents

The code in Listing 1 also displays the contents of the dictionary using a for loop to iterate on a list of keys obtained by invoking the keys() method on the dictionary.  (This methodology was explained in the earlier lesson entitled "Learn to Program using Python:  Valid Keys, Key Lists, Iteration.")

The output produced by the above code is shown in Listing 2 below.
 
Dictionary contents
Key  :  Value
to  :  string
5  :  number

Listing 2

Keys must be unique

Each of the keys within a dictionary must be unique.  If you make an assignment using an existing key as the index, the old value associated with that key is overwritten by the new value.  You can use this characteristic to advantage in order to modify an existing value for an existing key.

Modifying a value

You can modify key:value pairs using assignment with the key as an index into the dictionary.  If you assign a new value using an existing key, the new value overwrites the value previously associated with that key.  The new value can be of the same type as the original value, or it can be a different type.

As shown in the program output in Listing 2 above, the value associated with the key 5 is the value number.  Thus, the value is a string.  (Note that 5 is a key here, and is not an ordinal index as is used with sequences such as lists or strings.)

The boldface line of code in Listing 3 below assigns a new value to the key 5 (changing the value associated with the key and not the key itself).  In this case, the type of the value is not a string as before.  Rather, it is a tuple.
 
# Overwrite existing value with a tuple
# value
d1[5]=("ab","cd","ef")
print "New dictionary contents"
print "Key",' : ',"Value"
for x in d1.keys():print x,' : ',d1[x]
print ""# Print blank line

Listing 3

Display the new value in the dictionary

The remaining code in Listing 3 uses the same iterative technique as before to display the keys in the dictionary along with their associated values.

Listing 4 below shows the output produced by this code.  Compare this output with the output shown in Listing 2 above.  (I have highlighted the new tuple value in boldface to make it easy for you to identify.)
 
New dictionary contents
Key  :  Value
to  :  string
5  :  ('ab', 'cd', 'ef')

Listing 4

A dictionary can shrink or grow as needed

If you make an assignment using a new key as the index, the new key:value pair will be added to the dictionary.  Thus, the size of a dictionary can increase at runtime.  (If you delete an element, the size can decrease.  I will illustrate this in a subsequent lesson.)

The next portion of this program increases the size of the dictionary by adding a new key:value pair.

Using a tuple as a key

A key must be immutable.  You can use a tuple as a key if all of the elements contained in the tuple are immutable.  (If the tuple contains mutable objects, it cannot be used as a key.)  Hence a tuple to be used as a key can contain strings, numbers, and other tuples containing references to immutable objects.

The boldface statement in Listing 5 below adds a new key:value pair to the dictionary using a two-element tuple as a key.
 
# Add a key value pair with a tuple as
# a key
print "Index with a tuple"
d1[(1,"a")] = "tuple"
print "New dictionary contents"
print "Key",' : ',"Value"
for x in d1.keys():print x,' : ',d1[x]
print ""# Print blank line

Listing 5

The tuple used as a key in Listing 5 contains a number and a string, both of which are immutable.  Therefore, this tuple is a valid key since all of its elements are immutable.

The remaining code in Listing 5 displays the new value in the dictionary.

Display the dictionary

Listing 6 below shows the output produced by the code in Listing 5 above.
 
Index with a tuple
New dictionary contents
Key  :  Value
(1, 'a')  :  tuple
to  :  string
5  :  ('ab', 'cd', 'ef')


Listing 6

The new information in the output is the line highlighted in boldface in Listing 6.  This line shows the tuple as the key and a string containing the word tuple as a value.  (Recall that the positions of the key:value pairs in a dictionary are randomized.  Therefore, the new element in the dictionary is not positioned at the end of the dictionary.)

Several combinations

At this point, the keys in the dictionary consist of one number, one string, and one tuple.  The tuple contains only immutable elements.

Similarly, the values in the dictionary consist of one tuple and two strings.  The values in a dictionary can be any type.  The keys can be any immutable type.

A tuple with mutable elements

You cannot use a list as a key because a list is mutable.  Similarly, you cannot use a tuple as a key if any of its elements are lists. (You can only use a tuple as a key if all of its elements are immutable.)

The code in Listing 7 below attempts, unsuccessfully, to use a tuple containing a list as a key.
 
# A tuple containing a list is not a 
# valid key
print "Try to index with a"
print " tuple containing a list"
d1[(1,"a",["b","c"])] = "tuple"

Listing 7

Display the output

The output produced by the code in Listing 7 is shown in Listing 8 below.  As you can see, this code caused the program to terminate with an unhashable type error.
 
Try to index with a
 tuple containing a list
Traceback (innermost last):
  File "Dict06.py", line 39, in ?
    d1[(1,"a",["b","c"])] = "tuple"
TypeError: unhashable type

Listing 8

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 string.

Ans:  See Listing 1.

2.  Describe five general characteristics of a dictionary.

Ans:

  1. A dictionary is an unordered collection of objects.
  2. Values are accessed using a key.
  3. A dictionary can shrink or grow as needed.
  4. The contents of dictionaries can be modified.
  5. Dictionaries can be nested.
  6. Sequence operations such as slice cannot be used with dictionaries.
3.  True or false?  The keys in a dictionary must be mutable.

Ans:  False.  The keys must be immutable.

4.  True or false?  You can iterate on a dictionary using its ordinal index.

Ans:  False.  Unlike strings, lists, and tuples, a dictionary doesn't have an ordinal index.  Rather, you index it using key values.

5.  True or false:  Because a dictionary doesn't have an ordinal index, it is not possible to iterate on it.

Ans:  False.  You can iterate on a dictionary using a special version of a for loop that reads something like the following (where d1 is the name of the dictionary):

for x in d1.keys():do something

6.  True or false?  Keys in a dictionary must be unique.

Ans:  True.  If you make an assignment using an existing key as the index, the old value associated with that key will be overwritten by the new value.

7.  How do you modify a value in a dictionary?

Ans:  You can modify key:value pairs using assignment with the key as an index into the dictionary.  If you assign a new value using an existing key, the new value overwrites the value previously associated with that key.

8.  True or false?  When you modify a value in a dictionary, the type of the new value must be the same as the type of the old value.

Ans:  False.  The new value can be the same type as the old value, or it can be a different type.

9.  True or false?  In the following statement, where d1 is the name of a dictionary, the use of 5 as an index causes the sixth element in the dictionary to be accessed.

d1[5]=("ab","cd","ef")

Ans:  False.  In this case, the 5 is simply an immutable key and has nothing to do with an ordinal index.

10.  True or false?  The size of a dictionary is fixed when the dictionary is originally created and cannot change thereafter.

Ans:  False.  A dictionary can shrink or grow as needed.  When you add new elements, it can grow to accommodate those new elements.  When you delete elements, it can shrink.  Growing and shrinking is automatic.

11.  True or false?  A tuple can never be used as a key in a dictionary.

Ans:  False.  A tuple can be used as a key so long as all of its elements are immutable.

12.  True or false?  A tuple containing a list cannot be used as a key in a dictionary.

Ans:  True.  A list is mutable.  Therefore, a tuple containing a list cannot be used as a key in a dictionary.

13.  True or false?  When you display the contents of a dictionary, the elements will be displayed in the same order that they were added to the dictionary.

Ans:  False.  The order of the contents of a dictionary is purposely randomized.

Listing of Sample Program

A complete listing of the program is shown in Listing 9.
 
# File Dict06.py
# Rev 12/23/00
# Copyright 2000, R. G. Baldwin
# Illustrates 
#   Overwriting values
#   Valid tuple key
#   Invalid tuple key
#------------------------------------//
# Create initialized dictionary
d1 = {5:"number","to":"string"}
print "Dictionary contents"
print "Key",' : ',"Value"
for x in d1.keys():print x,' : ',d1[x]
print ""# Print blank line

# Overwrite existing value with a tuple
# value
d1[5]=("ab","cd","ef")
print "New dictionary contents"
print "Key",' : ',"Value"
for x in d1.keys():print x,' : ',d1[x]
print ""# Print blank line
              
# Add a key value pair with a tuple as
# a key
print "Index with a tuple"
d1[(1,"a")] = "tuple"
print "New dictionary contents"
print "Key",' : ',"Value"
for x in d1.keys():print x,' : ',d1[x]
print ""# Print blank line

# A tuple containing a list is not a 
# valid key
print "Try to index with a"
print " tuple containing a list"
d1[(1,"a",["b","c"])] = "tuple"


Listing 9



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-