15.04.2013 Views

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

dict2 = {'name': 'earth', 'port': 80}<br />

>>><br />

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

... print 'key=%s, value=%s' % (key, dict2[key])<br />

...<br />

key=name, value=earth<br />

key=port, value=80<br />

Beginning with <strong>Python</strong> 2.2, you no longer need to use the keys() method to extract a list of keys to loop<br />

over. Iterators were created to simplify accessing of sequence-like objects such as dictionaries and files.<br />

Using just the dictionary name itself will cause an iterator over that dictionary to be used in a for loop:<br />

>>> dict2 = {'name': 'earth', 'port': 80}<br />

>>><br />

>>>> for key in dict2:<br />

... print 'key=%s, value=%s' % (key, dict2[key])<br />

...<br />

key=name, value=earth<br />

key=port, value=80<br />

To access individual dictionary elements, you use the familiar square brackets along with the key to<br />

obtain its value:<br />

>>> dict2['name']<br />

'earth'<br />

>>><br />

>>> print 'host %s is running on port %d' % \<br />

... (dict2['name'], dict2['port'])<br />

host earth is running on port 80<br />

Dictionary dict1 defined above is empty while dict2 has two data items. The keys in dict2 are 'name'<br />

and 'port', and their associated value items are 'earth' and 80, respectively. Access to the value is<br />

through the key, as you can see from the explicit access to the 'name' key.<br />

If we attempt to access a data item with a key that is not part of the dictionary, we get an error:<br />

>>> dict2['server']<br />

Traceback (innermost last):<br />

File "", line 1, in ?<br />

KeyError: server<br />

In this example, we tried to access a value with the key 'server' which, as you know from the code<br />

above, does not exist. The best way to check if a dictionary has a specific key is to use the dictionary's<br />

has_key() method, or better yet, the in or not in operators starting with version 2.2. The has_key()<br />

method will be obsoleted in future versions of <strong>Python</strong>, so it is best to just use in or not in.

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

Saved successfully!

Ooh no, something went wrong!