Online Book Reader

Home Category

Learning Python - Mark Lutz [131]

By Root 1379 0
the sequence operations that work on strings and lists. Because dictionaries are unordered collections, operations that depend on a fixed positional order (e.g., concatenation, slicing) don’t make sense. Instead, dictionaries are the only built-in representatives of the mapping type category (objects that map keys to values).

Tables of object references (hash tables)

If lists are arrays of object references that support access by position, dictionaries are unordered tables of object references that support access by key. Internally, dictionaries are implemented as hash tables (data structures that support very fast retrieval), which start small and grow on demand. Moreover, Python employs optimized hashing algorithms to find keys, so retrieval is quick. Like lists, dictionaries store object references (not copies).

Table 8-2 summarizes some of the most common and representative dictionary operations (again, see the library manual or run a dir(dict) or help(dict) call for a complete list—dict is the name of the type). When coded as a literal expression, a dictionary is written as a series of key:value pairs, separated by commas, enclosed in curly braces.[24] An empty dictionary is an empty set of braces, and dictionaries can be nested by writing one as a value inside another dictionary, or within a list or tuple.

Table 8-2. Common dictionary literals and operations

Operation

Interpretation

D = {}

Empty dictionary

D = {'spam': 2, 'eggs': 3}

Two-item dictionary

D = {'food': {'ham': 1, 'egg': 2}}

Nesting

D = dict(name='Bob', age=40)

D = dict(zip(keyslist, valslist))

D = dict.fromkeys(['a', 'b'])

Alternative construction techniques:

keywords, zipped pairs, key lists

D['eggs']

D['food']['ham']

Indexing by key

'eggs' in D

Membership: key present test

D.keys()

D.values()

D.items()

D.copy()

D.get(key, default)

D.update(D2)

D.pop(key)

Methods: keys,

values,

keys+values,

copies,

defaults,

merge,

delete, etc.

len(D)

Length: number of stored entries

D[key] = 42

Adding/changing keys

del D[key]

Deleting entries by key

list(D.keys())

D1.keys() & D2.keys()

Dictionary views (Python 3.0)

D = {x: x*2 for x in range(10)}

Dictionary comprehensions (Python 3.0)

* * *

[24] As with lists, you won’t often see dictionaries constructed using literals. Lists and dictionaries are grown in different ways, though. As you’ll see in the next section, dictionaries are typically built up by assigning to new keys at runtime; this approach fails for lists (lists are commonly grown with append instead).

Dictionaries in Action

As Table 8-2 suggests, dictionaries are indexed by key, and nested dictionary entries are referenced by a series of indexes (keys in square brackets). When Python creates a dictionary, it stores its items in any left-to-right order it chooses; to fetch a value back, you supply the key with which it is associated, not its relative position. Let’s go back to the interpreter to get a feel for some of the dictionary operations in Table 8-2.

Basic Dictionary Operations

In normal operation, you create dictionaries with literals and store and access items by key with indexing:

% python

>>> D = {'spam': 2, 'ham': 1, 'eggs': 3} # Make a dictionary

>>> D['spam'] # Fetch a value by key

2

>>> D # Order is scrambled

{'eggs': 3, 'ham': 1, 'spam': 2}

Here, the dictionary is assigned to the variable D; the value of the key 'spam' is the integer 2, and so on. We use the same square bracket syntax to index dictionaries by key as we did to index lists by offset, but here it means access by key, not by position.

Notice the end of this example: the left-to-right order of keys in a dictionary will almost always be different from what you originally typed. This is on purpose: to implement fast key lookup (a.k.a. hashing), keys need to be reordered in memory. That’s why operations that assume a fixed left-to-right order (e.g., slicing, concatenation) do not apply to dictionaries; you can fetch values

Return Main Page Previous Page Next Page

®Online Book Reader