Published: January 15, 2001
By Richard G. Baldwin
Python Programming Lesson #76
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.
This lesson will teach you how to
Some of these characteristics were illustrated in previous lessons. Other characteristics will be illustrated using the sample programs in this and subsequent lessons.
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.
Three initialized dictionaries
The code in Listing 1 creates three initialized dictionaries named
d1,
d2,
and d3. Each of these dictionary objects contains three elements.
print "Show nesting" d1 = {1:10,2:20,3:30} d2 = {1:40,2:50,3:60} d3 = {1:70,2:80,3:90} Listing 1 |
Each element in each of the three dictionary objects created in Listing 1 has a number for its key, and also has a number for its value.
Recall that a key can be any immutable object and a valuecan be any object. Numbers were used here for simplicity. Don't confuse these numeric keys with ordinal indices. These numbers have nothing to do with ordinal indices. Rather, they are simply key values.
Nesting the dictionaries
The single statement in Listing 2 below creates a new dictionary object
named d4. This object contains three elements. The value
of each element is one of the dictionary objects created in Listing 1 above.
(I
highlighted them using boldface to make them easy to spot.)
d4 = {"a":d1,"b":d2,"c":d3} Listing 2 |
The keys for each of the three elements in Listing 2 are strings. Again, the keys could be any immutable objects. I used strings in this case to make it easy to identify them when examining the contents of the dictionary later.
Display the dictionary contents
The code in Listing 3 below uses nested for loops to iterate
on the dictionary named d4 and each of the dictionaries nested in
d4
to extract and display the contents of those nested dictionaries.
for x in d4.keys(): print "KEY",'\t',"VALUE" print x,'\t',d4[x] print " key",'\t',"value" for y in d4[x].keys():\ print " ",y,'\t',d4[x][y] Listing 3 |
The display methodology
A somewhat simpler version of the methodology used to display the contents of the nested dictionaries was explained in the earlier lesson entitled Learn to Program using Python: Valid Keys, Key Lists, Iteration.
The big difference here is the use of nested for loops. The outer loop iterates on the dictionary named d4 extracting each nested dictionary in turn. The inner loop is used to iterate on each nested dictionary when it is extracted. If the loop logic in this display code escapes you at this point, don't worry too much about it. I will address that logic in more detail in a subsequent lesson on loops.
The output
Listing 4 below shows the output produced by the code in Listing 3
above. (Color was added for emphasis.)
Show nesting KEY VALUE b {3: 60, 2: 50, 1: 40} key value 3 60 2 50 1 40 KEY VALUE c {3: 90, 2: 80, 1: 70} key value 3 90 2 80 1 70 KEY VALUE a {3: 30, 2: 20, 1: 10} key value 3 30 2 20 1 10 Listing 4 |
Why red and blue?
Although the print statements in Listing 3 above didn't produce color in the output, I added color to help you correlate the output with the code.
The three blue print statements in the code produced the output shown in blue. Likewise, the single red print statement in the code produced the output shown in red.
Output from the outer loop
The three blue print statements are in the outer loop. Each of these print statements produced one line of output during each iteration. The outer loop iterated once for each of the three dictionaries nested in the dictionary object named d4. Hence, there are nine blue lines in the output.
The first blue print statement caused some column headers to be printed in uppercase (this statement was executed three times).
The second blue print statement caused each of the keys (b, c, a) in the dictionary object named d4 to be printed (in random order) along with the value associated with each of those keys.
The third blue print statement caused some more column headers to be printed in lowercase (also executed three times).
Output from the inner loop
The red print statement in the inner loop in Listing 3 produced one line of output for each element in each nested dictionary element. Each line of output consisted of the key for that element and the value associated with that key. Hence, there are nine red lines in the output produced for the three nested dictionary objects, each of which has three elements.
Now let's put the nested for loop aside and consider a different topic.
Removing elements from a dictionary
The del statement can be used to remove an element from a dictionary
as shown in Listing 5.
print '\n',"Show deletion/values/sort" del d1[1] del d2[2] del d3[3] Listing 5 |
Each of the three del statements in Listing 5 removes one element from a dictionary that is nested in the dictionary named d4. (Note that even though these dictionaries have been nested in the dictionary named d4, they are still accessible using their names: d1, d2, and d3.)
Each of the three dictionaries nested in d4 contained three elements before the three del statements were executed, and contained only two elements after the three del statements were executed.
Getting and sorting keys
The code shown in Listing 6 invokes the keys() method to get
a list of keys for the dictionary named d4. It stores a reference
to that list in L1. Then it invokes the sort() method
to sort those keys into alphanumeric order. (Alphanumeric order is like
alphabetic order, but also including an ordering for numbers and special
characters such as punctuation marks.)
L1 = d4.keys() L1.sort() Listing 6 |
When the list produced by the code in Listing 6 is used to iterate on the dictionary, the results should no longer be in random order. Rather, they should be in alphanumeric order.
Display the dictionary contents
The code in Listing 7 below is used to display the contents of the dictionary.
This code is similar to the code in the Listing 3 shown earlier with some
important differences.
for x in L1: print "KEY",'\t',"VALUE" print x,'\t',d4[x] print x," values =",d4[x].values() print " key",'\t',"value" L2 = d4[x].keys() L2.sort() for y in L2:\ print " ",y,'\t',d4[x][y] Listing 7 |
Differences in display code
The primary differences between the code in Listing 7 above and the code in Listing 3 shown earlier is:
Show deletion/values/sort KEY VALUE a {3: 30, 2: 20} a values = [30, 20] key value 2 20 3 30 KEY VALUE b {3: 60, 1: 40} b values = [60, 40] key value 1 40 3 60 KEY VALUE c {2: 80, 1: 70} c values = [80, 70] key value 1 70 2 80 Listing 8 |
Analyze the output
The important things to note about the output shown in Listing 8 are:
The has_key() method can be used to determine if the list of
keys for a dictionary contains a particular key. This is illustrated
in Listing 9.
print '\n',"Show membershp test" cnt = 0 while cnt < 5: if d1.has_key(cnt): print cnt,'\t',d1[cnt] cnt = cnt + 1 else: print "No key matches ",cnt cnt = cnt + 1 Listing 9 |
The logic in the code in Listing 9 is straightforward. The blue line (that begins a while loop) causes the lines below it to be executed for values of cnt equal to 0, 1, 2, 3, and 4 (cnt less than 5). The code following the blue line is an if-else statement.
During each of the five iterations of the while loop, the dictionary named d1 is tested in the red line (an if statement) to determine if it contains one of the keys 0, 1, 2, 3, and 4.
If the dictionary does contain a particular key, the code following the red line displays the key and the value associated with the key. Otherwise (else), the code following the green line displays the statement No key matches followed by the test key.
The output
The output produced by the code in Listing 9 above is shown in Listing
10 below. As you can see, matches were found for keys 2 and 3.
No matches were found for keys 0, 1, and 4. You should be able to
confirm this by examining the output shown earlier in Listing 8, which
shows the following key:value pairs for the first dictionary nested in
the dictionary named d4: {3: 30, 2: 20}.
Show membershp test No key matches 0 No key matches 1 2 20 3 30 No key matches 4 Listing 10 |
Ans: False. A dictionary can contain elements that are themselves dictionaries. This leads to the concept of nested dictionaries.
2. What is the name of the method that can be used to obtain a list of the keys of a dictionary?
Ans: The keys() method can be used to obtain a list of the keys in a dictionary.
3. True or false? When the keys() method is used to obtain a list of keys, the keys are in sorted order.
Ans: False. Dictionary keys are purposely randomized, and this is reflected in the list of keys obtained using the keys() method.
4. How can you obtain a list of dictionary keys in sorted order?
Ans: You can apply the sort() method to the list of keys.
5. What statement can be used to remove elements from a dictionary?
Ans: A del statement can be used to remove elements to a dictionary.
6. When the del statement is used to remove an element from a dictionary, the statement is applied to the value of the element.
Ans: False. The del statement is applied to the element's key.
7. What method can be used to determine if a particular element exists in a dictionary?
Ans: The has_key() method can be used to determine if a particular element is a member of a dictionary.
8. Write a program that illustrates how to create and initialize a dictionary with a list and a tuple.
Ans: See Listing 11 below.
# File Dict10.py # Rev 08/08/00 # Copyright 2000, R. G. Baldwin # Illustrates initializing a # dictionary #------------------------------- # Create initialized dictionary d1 = {5:[6,7,8],"a":(1,2,3)} # Display it print d1,'\n' Listing 11 |
9. Write a program that illustrates how to get a list of keys.
Ans: See Listing 12 below.
# 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 12 |
10. Write a program that illustrates how to iterate on a list of keys.
Ans: See Listing 13 below.
# 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 13 |
# File Dict08.py # Rev 12/23/00 # Copyright 2000, R. G. Baldwin # Illustrates # Nested dictionary # Sorting key list # Deleting items # has_key() membership #------------------------------------// print "Show nesting" d1 = {1:10,2:20,3:30} d2 = {1:40,2:50,3:60} d3 = {1:70,2:80,3:90} d4 = {"a":d1,"b":d2,"c":d3} for x in d4.keys(): print "KEY",'\t',"VALUE" print x,'\t',d4[x] print " key",'\t',"value" for y in d4[x].keys():\ print " ",y,'\t',d4[x][y] # Delete some items # Sort the keys print '\n',"Show deletion/values/sort" del d1[1] del d2[2] del d3[3] L1 = d4.keys() L1.sort() for x in L1: print "KEY",'\t',"VALUE" print x,'\t',d4[x] print x," values =",d4[x].values() print " key",'\t',"value" L2 = d4[x].keys() L2.sort() for y in L2:\ print " ",y,'\t',d4[x][y] print '\n',"Show membershp test" cnt = 0 while cnt < 5: if d1.has_key(cnt): print cnt,'\t',d1[cnt] cnt = cnt + 1 else: print "No key matches ",cnt cnt = cnt + 1 Listing 14 |
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-