Learn to Program using Python: Working with Dictionary Elements

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.

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 of a dictionary. Subsequent lessons have taught you how to perform other operations on dictionaries.

This lesson will teach you how to

Nest dictionaries

Sort key lists

Delete elements from dictionaries

Do membership testing on dictionaries

What Is a Dictionary?

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

A dictionary is an unordered collection of objects.

Values are accessed using a key.

A dictionary can shrink or grow as needed.

The contents of dictionaries can be modified.

Dictionaries can be nested.

Sequence operations such as slice cannot be used with dictionaries.

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 14 near the end of the lesson shows a Python script that:

Creates, initializes, and displays a dictionary containing other nested dictionaries.

Deletes some elements from the dictionary and displays the modified dictionary after sorting the dictionary keys.

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.

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 outputListing 4 below shows the output produced by the code in Listing 3 above. (Color was added for emphasis.)

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.

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.

The primary differences between the code in Listing 7 above and the code in Listing 3 shown earlier is:

The keys for the dictionary named d4 are obtained, sorted, and stored in a list named L1 (shown in Listing 6) outside the outer loop. The sorted list is used for iteration control in the outer for loop in Listing 7.

An extra print statement (shown in blue) is in the outer loop. This statement illustrates the use of the values() method to obtain and display a list of the values contained in each nested dictionary.

A list of keys for each nested dictionary is obtained and sorted (shown in red). The sorted list is used for iteration control in the inner for loop.

The output produced by the code in Listing 7 above is shown in Listing 8 below (color added for emphasis).

The blue lines of output correspond to the blue statement in the code shown in Listing 7.

The data is displayed in order of ascending keys. The outer loop iterates on the keys in the order a, b, and c. The inner loop iterates on the keys in the order 1, 2, and 3. (Note however that there are some missing keys in the data displayed by the inner loop as a result of the application of the del statement earlier.)

Key membership testing

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.

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

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.