15.04.2013 Views

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

[d] New in <strong>Python</strong> 2.2.<br />

[e] New in <strong>Python</strong> 2.0.<br />

Below, we showcase some of the more common dictionary methods. We have already seen has_key()<br />

and its replacements in and not in at work above. Attempting to access a nonexistent key will result in<br />

an exception (KeyError) as we saw in Section 7.1.<br />

Basic dictionary methods focus on their keys and values. These are keys(), which returns a list of the<br />

dictionary's keys, values(), which returns a list of the dictionary's values, and items(), which returns a<br />

list of (key, value) tuple pairs. These are useful when you wish to iterate through a dictionary's keys or<br />

values, albeit in no particular order.<br />

>>> dict2.keys()<br />

['port', 'name']<br />

>>><br />

>>> dict2.values()<br />

[80, 'earth']<br />

>>><br />

>>> dict2.items()<br />

[('port', 80), ('name', 'earth')]<br />

>>><br />

>>> for eachKey in dict2.keys():<br />

... print 'dict2 key', eachKey, 'has value', dict2[eachKey]<br />

...<br />

dict2 key port has value 80<br />

dict2 key name has value earth<br />

The keys() method is fairly useful when used in conjunction with a for loop to retrieve a dictionary's<br />

values as it returns a list of a dictionary's keys. However, because its items (as with any keys of a hash<br />

table) are unordered, imposing some type of order is usually desired.<br />

In <strong>Python</strong> versions prior to 2.4, you would have to call a dictionary's keys() method to get the list of its<br />

keys, then call that list's sort() method to get a sorted list to iterate over. Now a built-in function<br />

named sorted(), made especially for iterators, exists, which returns a sorted iterator:<br />

>>> for eachKey in sorted(dict2):<br />

... print 'dict2 key', eachKey, 'has value',<br />

dict2[eachKey]<br />

...<br />

dict2 key name has value earth<br />

dict2 key port has value 80<br />

The update() method can be used to add the contents of one directory to another. Any existing entries<br />

with duplicate keys will be overridden by the new incoming entries. Nonexistent ones will be added. All<br />

entries in a dictionary can be removed with the clear() method.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!