Section 7.2. Mapping Type Operators


7.2. Mapping Type Operators

Dictionaries will work with all of the standard type operators but do not support operations such as concatenation and repetition. Those operations, although they make sense for sequence types, do not translate to mapping types. In the next two subsections, we introduce you to the operators you can use with dictionaries.

7.2.1. Standard Type Operators

The standard type operators were introduced in Chapter 4. Here are some basic examples using some of those operators:

>>> dict4 = {'abc': 123} >>> dict5 = {'abc': 456} >>> dict6 = {'abc': 123, 98.6: 37} >>> dict7 = {'xyz': 123} >>> dict4 < dict5 True >>> (dict4 < dict6) and (dict4 < dict7) True >>> (dict5 < dict6) and (dict5 < dict7) True >>> dict6 < dict7 False


How are all these comparisons performed? Like lists and tuples, the process is a bit more complex than it is for numbers and strings. The algorithm is detailed in Section 7.3.1.

7.2.2. Mapping Type Operators

Dictionary Key-Lookup Operator ( [ ] )

The only operator specific to dictionaries is the key-lookup operator, which works very similarly to the single element slice operator for sequence types.

For sequence types, an index offset is the sole argument or subscript to access a single element of a sequence. For a dictionary, lookups are by key, so that is the argument rather than an index. The key-lookup operator is used for both assigning values to and retrieving values from a dictionary:

d[k] = v     # set value 'v' in dictionary with key 'k' d[k]         # lookup value in dictionary with key 'k'


(Key) Membership (in, not in)

Beginning with Python 2.2, programmers can use the in and not in operators to check key membership instead of the has_key() method:

>>> 'name' in dict2 True >>> 'phone' in dict2 False




Core Python Programming
Core Python Programming (2nd Edition)
ISBN: 0132269937
EAN: 2147483647
Year: 2004
Pages: 334
Authors: Wesley J Chun

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net