next up previous contents
Next: Input and Output Up: Lists, Tuples and Dictionaries Previous: Dictionaries   Contents

Functions and Methods for Dictionaries

As is the case for strings and lists, the len function returns the number of elements in a dictionary, that is, the number of key/value pairs. In addition, a number of methods for dictionaries are available.

Since refering to a non-existent key in a dictionary raises a KeyError exception, you should avoid indexing a dictionary unless you're sure of the existence of an entry with the key you are using. One alternative is to use a try/except clause (Section 1.4.5) to trap the KeyError. Two methods are also useful in this situation. The has_key method returns 1 (true) if the specified dictionary has the key which the method accepts as an argument, and 0 (false) otherwise. Thus, an if clause (Section 6.4) can be used to take action if a specified key does not exists. The get method also accepts a key as an argument, but it returns the value stored in the dictionary under that key if it exists, or an optional second argument if there is no value for the key provided. With only one argument, get returns the value None when there is no value corresponding to the key provided.

As an illustration of these methods, suppose we are counting how many times a word appears in a file by using each word as a key to a dictionary called counts, and storing the number of times the word appears as the corresponding value. The logic behind the program would be to add one to the value if it already exists, or to set the value to one if it does not, since that will represent the first time the word is encountered. Here are three code fragments illustrating the different ways of handling a value stored in word which may or may not already be a key in the dictionary. (Remember that counts would have to be initialized to an empty dictionary before any elements could be added to it.)

# method 1: exceptions
        try:
                counts[word] = counts[word] + 1
        except KeyError:
                counts[word] = 1                      

# method 2: check with has_key
        if counts.has_key(word):
                counts[word] = counts[word] + 1
        else:
                counts[word] = 1                      

# method 3: use get
        counts[word] = counts.get(word,0) + 1
Although the third method is the shortest, it may not be obvious why it works. When an entry with the specified key already exists, the get method will return that entry and increment it by 1. If the key does not exist, the optional second argument to get forces it to return a value of 0, which, when incremented by 1 gives the correct initial value.

As of version 2.2, it is possible to iterate over a dictionary using a for loop; the operation will return the keys of the dictionary in an arbitrary order. In addition, the in operator can be used as an alternative to the has_key method to determine if a particular key is present in a dictionary.

A few other methods provide alternative ways of accessing the keys, values or key/value pairs of a dictionary. The keys method returns a list of just the keys of a dictionary, and the values method returns a list of just the values. While the returned lists have their elements stored in an arbitrary order, corresponding elements in the two lists will be key/value pairs. The items method returns a list of tuples consisting of all the key/value pairs. Returning to the example using names as keys and phone numbers as values, here are the results of invoking these three methods on the phonedict dictionary:

>>> phonedict = {'Fred':'555-1231','Andy':'555-1195','Sue':'555-2193'}    
>>> phonedict.keys()
['Fred', 'Sue', 'Andy']
>>> phonedict.values()
['555-1231', '555-2193', '555-1195']
>>> phonedict.items()
[('Fred', '555-1231'), ('Sue', '555-2193'), ('Andy', '555-1195')]

To remove all the elements of a dictionary, use the clear method. This differs from using the del operator on the dictionary in that the dictionary, although empty, still exists. To make a copy of a dictionary, use the copy method; remember that assignment of a dictionary to another variable may not do what you think (Section 6.1).

Python provides the update method to allow your to merge all the key/value pairs in one dictionary with those in another. If the original dictionary has an entry with the same key as one in the dictionary used for updating, the value from the dictionary used for updating will be placed in the original dictionary.

>>> master = {'orange':3,'banana':5,'grapefruit':2}
>>> slave = {'apple':7,'grapefruit':4,'nectarine':3}
>>> master.update(slave)
>>> master
{'banana': 5, 'orange': 3, 'nectarine': 3, 'apple': 7, 'grapefruit': 4}
Since both master and slave had entries for the key ``grapefruit'', the value found in master after the call to update is the one which was in slave.
next up previous contents
Next: Input and Output Up: Lists, Tuples and Dictionaries Previous: Dictionaries   Contents
Phil Spector 2003-11-12