Online Book Reader

Home Category

Learning Python - Mark Lutz [588]

By Root 1619 0
Index a dictionary by key

2

>>> D = {'x':1, 'y':2, 'z':3}

>>> D['w'] = 0 # Create a new entry

>>> D['x'] + D['w']

1

>>> D[(1,2,3)] = 4 # A tuple used as a key (immutable)

>>> D

{'w': 0, 'z': 3, 'y': 2, (1, 2, 3): 4, 'x': 1}

>>> list(D.keys()), list(D.values()), (1,2,3) in D # Methods, key test

(['w', 'z', 'y', (1, 2, 3), 'x'], [0, 3, 2, 4, 1], True)

# Empties

>>> [[]], ["",[],(),{},None] # Lots of nothings: empty objects

([[]], ['', [], (), {}, None])

Indexing and slicing. Indexing out of bounds (e.g., L[4]) raises an error; Python always checks to make sure that all offsets are within the bounds of a sequence.

On the other hand, slicing out of bounds (e.g., L[-1000:100]) works because Python scales out-of-bounds slices so that they always fit (the limits are set to zero and the sequence length, if required).

Extracting a sequence in reverse, with the lower bound greater than the higher bound (e.g., L[3:1]), doesn’t really work. You get back an empty slice ([ ]) because Python scales the slice limits to make sure that the lower bound is always less than or equal to the upper bound (e.g., L[3:1] is scaled to L[3:3], the empty insertion point at offset 3). Python slices are always extracted from left to right, even if you use negative indexes (they are first converted to positive indexes by adding the sequence length). Note that Python 2.3’s three-limit slices modify this behavior somewhat. For instance, L[3:1:-1] does extract from right to left:>>> L = [1, 2, 3, 4]

>>> L[4]

Traceback (innermost last):

File "", line 1, in ?

IndexError: list index out of range

>>> L[-1000:100]

[1, 2, 3, 4]

>>> L[3:1]

[]

>>> L

[1, 2, 3, 4]

>>> L[3:1] = ['?']

>>> L

[1, 2, 3, '?', 4]

Indexing, slicing, and del. Your interaction with the interpreter should look something like the following code. Note that assigning an empty list to an offset stores an empty list object there, but assigning an empty list to a slice deletes the slice. Slice assignment expects another sequence, or you’ll get a type error; it inserts items inside the sequence assigned, not the sequence itself:>>> L = [1,2,3,4]

>>> L[2] = []

>>> L

[1, 2, [], 4]

>>> L[2:3] = []

>>> L

[1, 2, 4]

>>> del L[0]

>>> L

[2, 4]

>>> del L[1:]

>>> L

[2]

>>> L[1:2] = 1

Traceback (innermost last):

File "", line 1, in ?

TypeError: illegal argument type for built-in operation

Tuple assignment. The values of X and Y are swapped. When tuples appear on the left and right of an assignment symbol (=), Python assigns objects on the right to targets on the left according to their positions. This is probably easiest to understand by noting that the targets on the left aren’t a real tuple, even though they look like one; they are simply a set of independent assignment targets. The items on the right are a tuple, which gets unpacked during the assignment (the tuple provides the temporary assignment needed to achieve the swap effect):>>> X = 'spam'

>>> Y = 'eggs'

>>> X, Y = Y, X

>>> X

'eggs'

>>> Y

'spam'

Dictionary keys. Any immutable object can be used as a dictionary key, including integers, tuples, strings, and so on. This really is a dictionary, even though some of its keys look like integer offsets. Mixed-type keys work fine, too:>>> D = {}

>>> D[1] = 'a'

>>> D[2] = 'b'

>>> D[(1, 2, 3)] = 'c'

>>> D

{1: 'a', 2: 'b', (1, 2, 3): 'c'}

Dictionary indexing. Indexing a nonexistent key (D['d']) raises an error; assigning to a nonexistent key (D['d']='spam') creates a new dictionary entry. On the other hand, out-of-bounds indexing for lists raises an error too, but so do out-of-bounds assignments. Variable names work like dictionary keys; they must have already been assigned when referenced, but they are created when first assigned. In fact, variable names can be processed as dictionary keys if you wish (they’re made visible in module namespace or stack-frame dictionaries):>>> D = {'a':1, 'b':2, 'c':3}

>>> D['a']

1

>>> D['d']

Traceback (innermost last):

File "", line 1, in ?

KeyError: d

>>> D['d'] =

Return Main Page Previous Page Next Page

®Online Book Reader