Using Dictionaries


By now you probably realize that programmers love to organize information. You saw that lists and tuples let you organize things into sequences. Well, dictionaries let you organize information too, but in a different way. With a dictionary, you don't store information in a sequence; instead, you store it in pairs. It's a lot like an actual dictionary where each entry is a pair: a word and its definition. When you look up a word, you get its definition. Python dictionaries work the same way: you look up a key and get its value.

Introducing the Geek Translator Program

The high-tech world has created many things that impact our lives, including a culture of its own. As the result of technology, new words and concepts have been born. There's a brand-new kind of slang out there, and the Geek Translator is here to help you understand the technophile in your life. The program creates a dictionary with geek terms and definitions. The program not only lets the user look up a term, but also add a term, replace a definition, and delete a term. Figure 5.10 illustrates the program.

click to expand
Figure 5.10: So "uninstalled" means fired. I was totally 404 on that.

Creating Dictionaries

The first thing I did in the program was create a dictionary of terms and definitions. The geek terms are on the left, and their definitions are on the right.

 # Geek Translator # Demonstrates using dictionaries # Michael Dawson - 2/16/03 geek = {"404" : "Clueless. From the web error message 404, meaning page not found.",          "Googling" : "Searching the Internet for background information on a person.",          "Keyboard Plaque" : "The collection of debris found in computer keyboards.",          "Link Rot" : "The process by which web page links become obsolete.",          "Percussive Maintenance" : "The act of striking an electronic device to make it work.",          "Uninstalled" : "Being fired. Especially popular during the dot-bomb era."} 

This code creates a dictionary named geek. It consists of six pairs, called items. As an example, one of the items is "Keyboard Plaque" : "The collection of debris found in computer keyboards." Each item is made up of a key and a value. The keys are on the left side of the colons. The values are on the right. So, "Keyboard Plaque" is a key, and its value is "The collection of debris found in computer keyboards." The key is literally the "key" to getting the value. That means you could use the key "Keyboard Plaque" to get its value "The collection of debris found in computer keyboards."

To create your own dictionary, follow the pattern I used. Type a key, followed by a colon, followed by the key's value. Use commas to separate all of the key-value pairs, and surround the whole thing with curly brackets. Like tuples and lists, you can either type the whole thing on one line or use separate lines after any of the commas.

Accessing Dictionary Values

The most common thing you'll do with a dictionary is use a key to get its value. There are a few different ways you can do this. I'll show you an example of each in this section, using the interactive interpreter.

Using a Key to Retrieve a Value

The simplest way to retrieve a value from a dictionary is by directly accessing it with a key. To get a key's value, just put the key in brackets, following the name of the dictionary. Here's an interactive session to show you what I mean (assume that I've already defined the dictionary geek):

 >>> geek["404"] 'clueless. From the web error message 404, meaning page not found.' >>> geek["Link Rot"] 'the process by which web page links become obsolete.' 

This looks similar to indexing a sequence, but there's an important difference. When you index a sequence, you use a position number. When you look up a value in a dictionary, you use a key. This is the only direct way to retrieve a value from a dictionary. In fact, dictionaries don't have position numbers at all.

One thing that sometimes trips up beginning programmers is that a value can't be used to get a key in a dictionary. That would be like trying to use a definition to find a word in a real-life dictionary. Real-life dictionaries just aren't set up for that kind of thing, and neither are Python dictionaries. So remember, it's give a key and get a value, only.

TRAP

If you try to get a value from a dictionary by directly accessing it with a key that doesn't exist, you'll generate an error:

 >>> geek["Dancing Baloney"] Traceback (most recent call last):   File "<pyshell#3>", line 1, in ?     geek["Dancing Baloney"] KeyError: Dancing Baloney 

Since "Dancing Baloney" isn't a key in the dictionary, this results in an error. ("Dancing Baloney," by the way, means animated graphics and other visual effects that have no substantive value, often used by web designers to impress clients.)

Testing for a Key with the in Operator Before Retrieving a Value

Since using a nonexistent key can lead to an error, it's usually best not to directly access a dictionary without taking some precautions. One thing you can do is check to see if a key exists before attempting to retrieve its value. You can check for the existence of a key with the in operator:

 >>> if "Dancing Baloney" in geek:          print "I know what Dancing Baloney is."     else:          print "I have no idea what Dancing Baloney is." I have no idea what Dancing Baloney is. 

Because the dictionary doesn't contain "Dancing Baloney" as a key, the condition "Dancing Baloney" in geek is false. So, the computer says it doesn't know what it is.

You use the in operator with dictionaries much the same way you've used it with lists and tuples. You type the value your checking for, followed by in, followed by the dictionary. This creates a condition. The condition is true if the key is in the dictionary, otherwise it's false. This is a handy thing to do before trying to get a value. But remember, in only checks for keys; it can't check for values used this way.

TRAP

The in operator didn't work with dictionaries before Python 2.2. If you're using a version of Python before that, you can use the dictionary method has_key() to test for a key in a dictionary. Check out Table 5.2, later in the chapter, for a description of this dictionary method and a few others.

Table 5.2: SELECTED DICTIONARY METHODS

Method

Description

has_key(key)

Returns true if key is in the dictionary as a key. Otherwise it returns false.

get(key, [default])

Returns the value of key. If key doesn't exist, then the optional default is returned. If key doesn't exist and default isn't specified, then None is returned.

keys()

Returns a list of all the keys in a dictionary.

values()

Returns a list of all the values in a dictionary.

items()

Returns a list of all the items in a dictionary. Each item is a two-element tuple, where the first element is a key and the second element is the key's value.

Using the get() Method to Retrieve a Value

There's another way to retrieve a value from a dictionary. You can use the dictionary method get(). The method has a built-in safety net for handling situations where you ask for a value of a key that doesn't exist. If the key doesn't exist, the method returns a default value, which you can define. Take a look at another attempt:

 >>> print geek.get("Dancing Baloney", "I have no idea.") I have no idea. 

By using the get() method here, I was guaranteed to get a value back. If this term was in the dictionary as a key, then I'd get its definition. Since it wasn't, I got back the default value that I defined, the string "I have no idea."

To use the get() method, all you have to do is supply the key you're looking for followed by an optional default value. If the key is in the dictionary, you get its value. If the key isn't in the dictionary, you get the default value. But here's the twist: if you don't supply a default value (it's your option), then you get back None. Here's an example I created without providing a default value:

 >>> print geek.get("Dancing Baloney") None 

Setting Up the Program

Time to get back to the code for the Geek Translator program. After I created the geek dictionary, I implemented the menu system you've seen before, this time with five choices. Like before, if the user chooses 0, the computer says good-bye.

 choice = None while choice != "0":     print \     """     Geek Translator     0 - Quit     1 - Look Up a Geek Term     2 - Add a Geek Term     3 - Redefine a Geek Term     4 - Delete a Geek Term     """     choice = raw_input("Choice: ")     print     # exit     if choice == "0":         print "Good-bye." 

Getting a Value

If the user enters 1, the next section asks for a term to look up. The computer checks to see if the term is in the dictionary. If it is, the program accesses the dictionary, using the term as the key, gets its definition, and prints it out. If the term is not in the dictionary, the computer informs the user.

     # get a definition     elif choice == "1":         term = raw_input("What term do you want me to translate?: ")         if term in geek:             definition = geek[term]             print "\n", term, "means", definition         else:             print "\nSorry, I don't know", term 

Adding a Key-Value Pair

Dictionaries are mutable, so you can modify them. If the user enters 2, the next section adds a new term to the dictionary:

     # add a term-definition pair     elif choice == "2":         term = raw_input("What term do you want me to add?: ")         if term not in geek:             definition = raw_input("What's the definition?: ")             geek[term] = definition             print "\n", term, "has been added."         else:             print "\nThat term already exists! Try redefining it." 

The computer asks the user for the new term to add. If the term is not already in the dictionary, the computer gets the definition and adds the pair through the line:

             geek[term] = definition 

This creates a new item in geek. The term is the key and the definition is its value. This is exactly how you assign a new item to a dictionary. You use the dictionary, followed by the key, in square brackets, followed by the assignment operator, followed by the key's value.

I wrote the program so that the computer refuses to add a term if it's already in the dictionary. This is a safety measure I created to insure that the user doesn't accidentally overwrite an existing term. If the user really wants to redefine an existing term, he or she should choose menu option 3.

TRICK

A dash of pessimism is a good thing, at least when you're programming. As you saw here, I assumed that the user might try to add a new term without realizing it's already in the dictionary. If I hadn't checked for this, a user could overwrite a term without realizing it. When you're writing your own programs, try to think of things that could go wrong, then try to make sure your program can deal with them. So be a pessimist, just a little bit.

Replacing a Key-Value Pair

If the user enters 3, then the next section replaces an existing key-value pair:

     # redefine an existing term     elif choice == "3":         term = raw_input("What term do you want me to redefine?: ")         if term in geek:             definition = raw_input("What's the new definition?: ")             geek[term] = definition             print "\n", term, "has been redefined."         else:             print "\nThat term doesn't exist! Try adding it." 

To replace a key-value pair, I used the exact same line of code that I used for adding a new pair:

             geek[term] = definition 

Python replaces the current value (the definition) with the new one.

TRAP

If you assign a value to a dictionary using a key that already exists, Python replaces the current value without complaint. So you have to watch out, because you might overwrite the value of an existing key without realizing it.

Deleting a Key-Value Pair

If the user enters 4, then this elif block runs:

     # delete a term-definition pair     elif choice == "4":         term = raw_input("What term do you want me to delete?: ")         if term in geek:             del geek[term]             print "\nOkay, I deleted", term         else:             print "\nI can't do that!", term, "doesn't exist in the dictionary." 

The program asks the user for the geek term to delete. Next, the program checks to see if the term is actually in the dictionary, with the in operator. If it is, the item is deleted with

             del geek[term] 

This deletes the item with the key term from the dictionary geek. You can delete any item in a dictionary this way. Just put del in front of the dictionary followed by the key of the item you wish to delete in square brackets.

If the geek term doesn't exist in the first place, the else clause executes and the computer lets the user know.

TRAP

Trying to delete a dictionary item through a key that doesn't exist will give you an error. It's a smart move to be sure the key you're using exists.

Wrapping Up the Program

The final else clause lets the user know that he or she entered an invalid choice:

     # some unknown choice     else:         print "\nSorry, but", choice, "isn't a valid choice." raw_input("\n\nPress the enter key to exit.") 

Understanding Dictionary Requirements

There are a few things you should keep in mind when creating dictionaries:

  • A dictionary can't contain multiple items with the same key. Think again about a real dictionary. It becomes pretty meaningless if you can keep adding the same word with totally new definitions whenever you want.

  • A key has to be immutable. It can be a string, a number, or a tuple, which gives you lots of possibilities. A key has to be immutable because, if it weren't, you could sneak into a dictionary later and change its keys, possibly ending up with two identical keys. And you just learned you can't have that!

  • Values don't have to be unique. Also, values can be immutable. They can be anything you want.

There's even more you can do with dictionaries. Table 5.2 summarizes some useful methods that can help you get more out of this new type.




Python Programming for the Absolute Beginner
Python Programming for the Absolute Beginner, 3rd Edition
ISBN: 1435455002
EAN: 2147483647
Year: 2003
Pages: 194

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net