Next: Input and Output Up: Lists, Tuples and Dictionaries Previous: Dictionaries   Contents As is the case for strings and lists, the len function returns the number ofelements in a dictionary, that is, the number of key/value pairs. In addition, anumber of methods for dictionaries are available.
Since refering to a non-existent key in a dictionary raises a KeyErrorexception, you should avoid indexing a dictionary unless you're sure of the existenceof an entry with the key you are using. One alternative is to use a try/exceptclause (Section1.4.5) to trap the KeyError. Two methods are also usefulin 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 (Section6.4) can be used to take action if a specifiedkey 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 optionalsecond 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 tothe key provided.
As an illustration of these methods, suppose we are counting how many times a wordappears in a file by using each word as a key to a dictionary called counts,and storing the number of times theword 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 threecode fragments illustrating the different ways of handling a value stored in wordwhich may or may not already be a key in the dictionary. (Remember that counts would have to be initialized toan 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) + 1Although 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 methodwill return that entry and increment it by 1. If the key does not exist, the optionalsecond 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 forloop; the operation willreturn the keys of the dictionary in an arbitrary order. In addition, the inoperator 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/valuepairs 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. Whilethe returned lists have their elements stored in an arbitrary order, correspondingelements in the two lists will be key/value pairs. The items methodreturns 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 differsfrom using the del operator on the dictionary in that the dictionary, althoughempty, 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 youthink (Section6.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 entrywith 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 callto update is the one which was in slave.
Next: Input and Output Up: Lists, Tuples and Dictionaries Previous: Dictionaries   Contents Phil Spector2003-11-12