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.

<strong>Python</strong> dictionaries are implemented as resizeable hash tables. If you are familiar with Perl, then we can<br />

say that dictionaries are similar to Perl's associative arrays or hashes.<br />

We will now take a closer look at <strong>Python</strong> dictionaries. The syntax of a dictionary entry is key:value Also,<br />

dictionary entries are enclosed in braces ( { } ).<br />

How to Create and Assign Dictionaries<br />

Creating dictionaries simply involves assigning a dictionary to a variable, regardless of whether the<br />

dictionary has elements or not:<br />

>>> dict1 = {}<br />

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

>>> dict1, dict2<br />

({}, {'port': 80, 'name': 'earth'})<br />

In <strong>Python</strong> versions 2.2 and newer, dictionaries may also be created using the factory function dict().<br />

We discuss more examples later when we take a closer look at dict(), but here's a sneak peek for now:<br />

>>> fdict = dict((['x', 1], ['y', 2]))<br />

>>> fdict<br />

{'y': 2, 'x': 1}<br />

In <strong>Python</strong> versions 2.3 and newer, dictionaries may also be created using a very convenient built-in<br />

method for creating a "default" dictionary whose elements all have the same value (defaulting to None if<br />

not given), fromkeys():<br />

>>> ddict = {}.fromkeys(('x', 'y'), -1)<br />

>>> ddict<br />

{'y': -1, 'x': -1}<br />

>>><br />

>>> edict = {}.fromkeys(('foo', 'bar'))<br />

>>> edict<br />

{'foo': None, 'bar': None}<br />

How to Access Values in Dictionaries<br />

To traverse a dictionary (normally by key), you only need to cycle through its keys, like this:

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

Saved successfully!

Ooh no, something went wrong!