Python Programming Lesson #64
December 1, 2000
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. 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.)
Containers or collections
In previous lessons, you learned about strings, lists, and tuples. Dictionaries fall in the same general family as these three types of objects (containers or collections), but with significant differences.
Preview
This lesson will introduce you to the characteristics of the Python dictionary, and will show you how to use the basic characteristics. Subsequent lessons will show you how to use the characteristics of dictionaries beyond the basics.
A dictionary is a mutable unordered set of key:value pairs. Its values can contain references to any type of object.
In other languages, similar data structures are often called associative arrays or hash tables.
Not a sequence
Unlike the string, list, and tuple, a dictionary is not a sequence. The sequences are indexed by a range of ordinal numbers. Hence, they are ordered.
Indexed by keys, not numbers
Dictionaries are indexed by keys. According to the Python Tutorial, a key can be "any non-mutable type." Since strings and numbers are not mutable, you can always use a string or a number as a key in a dictionary.
What about a tuple as a key?
You can use a tuple as a key if all of the items contained in the tuple are immutable. Hence a tuple to be used as a key can contain strings, numbers, and other tuples containing references to immutable objects.
What about a list as a key?
You cannot use a list as a key because a list is mutable. That is to say, its contents can be modified using its append() method.
What does a dictionary look like?
You can create a dictionary as an empty pair of curly braces, {}.
Alternatively, you can initially populate a dictionary by placing a comma-separated list of key:value pairs within the braces.
Can I add key:value pairs later?
Later on, you can add new key:value pairs through indexing and assignment, using the new key as the index.
Keys must be unique, otherwise...
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.
New key:value pairs add to the dictionary
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.
Removing key:value pairs
You can use del to remove a key:value pair from a dictionary. Thus, the size of a dictionary can also shrink at runtime.
Add/modify key:value pairs
You add or modify key:value pairs using assignment with the key as an index into the dictionary.
Fetching values associated with keys
You extract a value from a dictionary using the associated key as an index. Attempting to extract a value using a non-existent key produces an error.
Getting a list of keys
You can obtain a list of all of the keys currently contained in a dictionary by invoking the keys() method on the dictionary. This produces a list of keys in random order. You can invoke the sort() method on the list to sort the keys if need be.
Membership testing
You can determine if a specific key is contained in the dictionary by invoking the has_key() method on the dictionary.
Getting a list of values
You can obtain a list of all of the values currently contained in a dictionary by invoking the values() method on the dictionary.
Use of boldface
I typically use boldface for emphasis in these lessons, although Python code is not written using boldface.
The empty dictionary
The boldface line in Listing 1 shows a statement that creates an empty
dictionary (I will illustrate creating an initializing a dictionary
at the same time in a subsequent lesson).
# File Dict02.py #------------------------------- # Create an empty dictionary d1 = {} # Print dictionary and length print "Dictionary contents" print d1 print "Length = ",len(d1) Listing 1 |
The remaining code in Listing 1 displays the empty dictionary and also gets and displays its length using len().
Let's see some output
The output produced by this code fragment is shown in Listing 2.
Dictionary contents {} Length = 0 Listing 2 |
As you can see from the boldface line in Listing 2, the empty dictionary is displayed as a pair of empty curly braces.
As you probably expected, the length of the dictionary at this point is reported to be zero.
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 two items d1["to"] = "two" d1["for"] = "four" # Print dictionary and length print "Dictionary contents" print d1 print "Length = ",len(d1) Listing 3 |
For example, the boldface line creates a new key:value pair with a key of "to" and a value of "two". Although I used a string for the key, I could have used any immutable type as explained earlier.
In the case, the value is a string. However, it could be any object of 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 and its length.
The output produced by this code fragment is shown in Listing 4.
Dictionary contents {'for': 'four', 'to': 'two'} Length = 2 Listing 4 |
Order is randomized
The contents of the modified dictionary are shown by the boldface line in Listing 4.
You will note that the dictionary now contains the two key:value pairs that I added.
You should also note that they do not appear in the same order that I added them.
According to Learning Python by Lutz and Ascher, "Python randomizes their order in order to provide quick lookup. Keys provide the symbolic (not physical) location of items in a dictionary."
Length is now 2
As you probably already guessed, Listing 4 shows the length of the modified dictionary to be 2. In other words, it now contains two key:value pairs.
Fetching a value
The boldface portion of Listing 5 shows indexing by key value to fetch
and display the value associated with the key "to".
# Get/display value by key print "Value for to = ",d1["to"] Listing 5 |
Other programming languages, such as Java, require you to invoke methods with names such as put() and get() to store and fetch key:value pairs. However, in Python, a simple indexing syntax is used for that purpose.
The output produced by this code fragment is shown in Listing 6.
Value for to = two Listing 6 |
As you have undoubtedly already figured out, the value associated with the key "to" is "two" (because that is the value that I stored there in Listing 3).
Ans: False. A dictionary is mutable because its existing items can be modified, new items can be added, and existing items can be deleted.
2. True or false? A dictionary is an unordered collection of objects.
Ans: True. The items in a dictionary are not maintained in any specific order, and a dictionary can contain references to any type of objects.
3. True or false: Sequence operations such as slicing and concatenation can be applied to dictionaries.
Ans: False. A dictionary is not a sequence. Because it is not maintained in any specific order, operations that depend on a specific order cannot be used.
4. True or false? Dictionaries are indexed using keys instead of ordinal offset values.
Ans: True.
5. True or false? Any object can be used as a valid key in a dictionary.
Ans: False. Only non-mutable types can be used as a key.
6. True or false? Because a tuple is non-mutable, any tuple can be used as a key in a dictionary.
Ans: False. A tuple can be used as a key only if all of the objects that it contains are also non-mutable.
7. True or false? Numbers and strings can always be used as keys.
Ans: True.
8. True or false? Lists can be used as keys.
Ans: False. Lists cannot be used as keys in a dictionary because they are mutable.
9. Describe the syntax of a dictionary.
Ans: A dictionary consists of none, one, or more key:value pairs, separated by commas, and enclosed in a pair of curly braces.
10. How do you add key:value pairs to an existing dictionary?
Ans: You can add new key:value pairs by using indexing and assignment, where the new key is the index.
11. True or false? If the addition of a new key:value pair causes the size of the dictionary to grow beyond its original size, an error occurs.
Ans: False. Dictionaries grow or shrink on an as-needed basis.
12. Can you remove key:value pairs from a dictionary, and if so, how?
Ans: You can use del to remove an existing key:value pair from a dictionary using the following syntax:
del dictionary[key]
13. Write a Python program that will:
14. True or false? You can obtain a sorted list of the keys currently contained in a dictionary by invoking the keys() method on the dictionary.
Ans: False. This will give you a list of keys, but they will not be sorted. You can sort them if need be by invoking the sort() method on the list.
15. True or false? You can determine if a specific key is contained in a dictionary by invoking the has_key() method on the dictionary.
Ans: True.
16. True or false? You can obtain a sorted list of the values currently contained in a dictionary by invoking the getValues() method on the dictionary.
Ans: False. You can obtain an unordered list of the
values by invoking the values() method on the dictionary.
# File Dict02.py # Rev 08/06/00 # Copyright 2000, R. G. Baldwin # Illustrates some basic # characteristics of # dictionaries #------------------------------- # Create an empty dictionary d1 = {} # Print dictionary and length print "Dictionary contents" print d1 print "Length = ",len(d1) # Add two items d1["to"] = "two" d1["for"] = "four" # Print dictionary and length print "Dictionary contents" print d1 print "Length = ",len(d1) # Get/display value by key print "Value for to = ",d1["to"] Listing 7 |
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.
-end-