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.

dict2['arch'] = 'sunos5' # add new entry<br />

>>><br />

>>> print 'host %(name)s is running on port %(port)d' %<br />

dict2<br />

host venus is running on port 6969<br />

If the key does exist, then its previous value will be overridden by its new value. The print statement<br />

above illustrates an alternative way of using the string format operator ( % ), specific to dictionaries.<br />

Using the dictionary argument, you can shorten the print request somewhat because naming of the<br />

dictionary occurs only once, as opposed to occurring for each element using a tuple argument.<br />

You may also add the contents of an entire dictionary to another dictionary by using the update() builtin<br />

method. We will introduce this method in Section 7.4.<br />

How to Remove Dictionary Elements and Dictionaries<br />

Removing an entire dictionary is not a typical operation. Generally, you either remove individual<br />

dictionary elements or clear the entire contents of a dictionary. However, if you really want to "remove"<br />

an entire dictionary, use the del statement (introduced in Section 3.5.5). Here are some deletion<br />

examples for dictionaries and dictionary elements:<br />

del dict2['name'] # remove entry with key 'name'<br />

dict2.clear() # remove all entries in dict1<br />

del dict2 # delete entire dictionary<br />

dict2.pop('name') # remove & return entry w/key<br />

<strong>Core</strong> Tip: Avoid using built-in object names as identifiers for<br />

variables!<br />

For those of you who began traveling in the <strong>Python</strong> universe before<br />

version 2.3, you may have once used dict as an identifier for a<br />

dictionary. However, because dict() is now a type and factory<br />

function, overriding it may cause you headaches and potential bugs.<br />

The interpreter will allow such overriding-hey, it thinks you seem<br />

smart and look like you know what you are doing! So be careful. Do<br />

NOT use variables named after built-in types like: dict, list, file,<br />

bool, str, input, or len!

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

Saved successfully!

Ooh no, something went wrong!