Text
stringlengths
1
9.41k
Comparisons never automatically convert types, except when comparing numeric type objects. In Python 3.0, this has changed: comparison of mixed types raises an exception instead of falling back on the fixed cross-type ordering.
Because sorting uses comparisons internally, this means that `[1, 2,` ``` 'spam'].sort() succeeds in Python 2.X but will raise an exception in ``` Python 3.0 and later. Python 3.0 also no longer supports passing in an arbitrary comparison _function to sorts, to implement different orderings.
The suggested work-_ around is to use the key=func keyword argument to code value transformations during the sort, and use the reverse=True keyword argument to change the sort order to descending.
These were the typical uses of comparison functions in the past. One warning here: beware that append and sort change the associated list object inplace, but don’t return the list as a result (technically, they both return a value called ``` None).
If you say something like L=L.append(X), you won’t get the modified value of L ``` (in fact, you’ll lose the reference to the list altogether!).
When you use attributes such as append and sort, objects are changed as a side effect, so there’s no reason to reassign. **|** ----- Partly because of such constraints, sorting is also available in recent Pythons as a builtin function, which sorts any collection (not just lists) and returns a new list for the resul...
The latter is applied temporarily during the sort, instead of changing the values to be sorted.
As we move along, we’ll see contexts in which the sorted builtin can sometimes be more useful than the sort method. Like strings, lists have other methods that perform other specialized operations.
For instance, reverse reverses the list in-place, and the extend and pop methods insert multiple items at the end of and delete an item from the end of the list, respectively.
There is also a reversed built-in function that works much like sorted, but it must be wrapped in a list call because it’s an iterator (more on iterators later): ``` >>> L = [1, 2] ``` `>>> L.extend([3,4,5])` _# Add many items at end_ ``` >>> L [1, 2, 3, 4, 5] ``` `>>> L.pop()` _# Delete and return last item_ `...
The end of the list serves as the top of the stack: ``` >>> L = [] ``` `>>> L.append(1)` _# Push onto stack_ ``` >>> L.append(2) >>> L [1, 2] ``` `>>> L.pop()` _# Pop off stack_ ``` 2 >>> L [1] ``` **|** ----- The pop method also accepts an optional offset of the item to be deleted and returned (the...
Other list methods remove an item by value (remove), insert an item at an offset (insert), search for an item’s offset (index), and more: ``` >>> L = ['spam', 'eggs', 'ham'] ``` `>>> L.index('eggs')` _# Index of an object_ ``` 1 ``` `>>> L.insert(1, 'toast')` _# Insert at position_ ``` >>> L ['spam', 'toast',...
Assigning an empty list to an index, on the other hand, just stores a reference to the empty list in the specified slot, rather than deleting it: ``` >>> L = ['Already', 'got', 'one'] >>> L[1:] = [] >>> L ['Already'] >>> L[0] = [] >>> L [[]] ``` Although all the operations just discussed are typical, the...
Mutability is an inherent property of each object type. ###### Dictionaries Apart from lists, dictionaries are perhaps the most flexible built-in data type in Python. If you think of lists as ordered collections of objects, you can think of dictionaries as unordered collections; the chief distinction is that in dicti...
Dictionaries also sometimes do the work of records and symbol tables used in other languages, can represent sparse (mostly empty) data structures, and much more.
Here’s a rundown of their main properties. Python dictionaries are: _Accessed by key, not offset_ Dictionaries are sometimes called associative arrays or hashes.
They associate a set of values with keys, so you can fetch an item out of a dictionary using the key under which you originally stored it.
You use the same indexing operation to get components in a dictionary as you do in a list, but the index takes the form of a key, not a relative offset. _Unordered collections of arbitrary objects_ Unlike in a list, items stored in a dictionary aren’t kept in any particular order; in fact, Python randomizes their left-...
Keys provide the symbolic (not physical) locations of items in a dictionary. _Variable-length, heterogeneous, and arbitrarily nestable_ Like lists, dictionaries can grow and shrink in-place (without new copies being made), they can contain objects of any type, and they support nesting to any depth (they can contain lis...
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 su...
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.[§] 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']) D['eggs'] D['food'][...
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). **|** ----- **Operation** **Interpretation** `del D[key]` Deleting entries by key ``` list(D.keys()) D1.keys() & D2.keys() ```...
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 dic...
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 only by key, not by position. The built-in len function works on dictionaries, too; it returns the number of items stored in the dictionary or, equivalently, the length of its...
The dictionary in membership operator allows you to test for key existence, and the keys method returns all the keys in the dictionary.
The latter of these can be useful for processing dictionaries sequentially, but you shouldn’t depend on the order of the keys list.
Because the keys result can be used as a normal list, however, it can always be sorted if order matters (more on sorting and dictionaries later): `>>> len(D)` _# Number of entries in dictionary_ ``` 3 ``` `>>> 'ham' in D` _# Key membership test alternative_ **|** ----- ``` True ``` `>>> list(D.keys())` _# Cr...
As mentioned earlier, the in membership test used for strings and lists also works on dictionaries—it checks whether a key is stored in the dictionary.
Technically, this works because dictionaries define iterators that step through their keys lists.
Other types provide iterators that reflect their common uses; files, for example, have iterators that read line by line.
We’ll discuss iterators in Chapters 14 and 20. Also note the syntax of the last example in this listing.
We have to enclose it in a list call in Python 3.0 for similar reasons—keys in 3.0 returns an iterator, instead of a physical list.
The list call forces it to produce all its values at once so we can print them. In 2.6, `keys builds and returns an actual list, so the` `list call isn’t needed to` display results.
More on this later in this chapter. The order of keys in a dictionary is arbitrary and can change from release to release, so don’t be alarmed if your dictionaries print in a different order than shown here.
In fact, the order has changed for me too—I’m running all these examples with Python 3.0, but their keys had a different order in an earlier edition when displayed.
You shouldn’t depend on dictionary key ordering, in either programs or books! ###### Changing Dictionaries In-Place Let’s continue with our interactive session.
Dictionaries, like lists, are mutable, so you can change, expand, and shrink them in-place without making new dictionaries: simply assign a value to a key to change or create an entry.
The del statement works here, too; it deletes the entry associated with the key specified as an index.
Notice also the nesting of a list inside a dictionary in this example (the value of the key 'ham').
All collection data types in Python can nest inside each other arbitrarily: ``` >>> D {'eggs': 3, 'ham': 1, 'spam': 2} ``` `>>> D['ham'] = ['grill', 'bake', 'fry']` _# Change entry_ ``` >>> D {'eggs': 3, 'ham': ['grill', 'bake', 'fry'], 'spam': 2} ``` `>>> del D['eggs']` _# Delete entry_ ``` >>> D {'ham':...
This doesn’t work for lists because Python` considers an offset beyond the end of a list out of bounds and throws an error.
To expand a list, you need to use tools such as the `append method or slice assignment` instead. ###### More Dictionary Methods Dictionary methods provide a variety of tools.
For instance, the dictionary values and ``` items methods return the dictionary’s values and (key,value) pair tuples, respectively ``` (as with keys, wrap them in a list call in Python 3.0 to collect their values for display): ``` >>> D = {'spam': 2, 'ham': 1, 'eggs': 3} >>> list(D.values()) [3, 1, 2] >>> list...
It’s an easy way to fill in a default for a key that isn’t present and avoid a missing-key error: `>>> D.get('spam')` _# A key that is there_ ``` 2 ``` `>>> print(D.get('toast'))` _# A key that is missing_ ``` None >>> D.get('toast', 88) 88 ``` The `update method provides something similar to concatenation f...
It merges the keys and values of one dictionary into another, blindly overwriting values of the same key: ``` >>> D {'eggs': 3, 'ham': 1, 'spam': 2} >>> D2 = {'toast':4, 'muffin':5} >>> D.update(D2) >>> D {'toast': 4, 'muffin': 5, 'eggs': 3, 'ham': 1, 'spam': 2} ``` Finally, the dictionary pop method delet...
It’s similar to the list `pop method, but it takes a key instead of an optional` position: ``` # pop a dictionary by key >>> D {'toast': 4, 'muffin': 5, 'eggs': 3, 'ham': 1, 'spam': 2} >>> D.pop('muffin') ``` **|** ----- ``` 5 ``` `>>> D.pop('toast')` _# Delete and return from a key_ ``` 4 >>> D {'...
In fact, dictionaries come with many more methods than those listed in Table 8-2; see the Python library manual or other documentation sources for a comprehensive list. ###### A Languages Table Let’s look at a more realistic dictionary example.
The following example creates a table that maps programming language names (the keys) to their creators (the values).
You fetch creator names by indexing on language names: ``` >>> table = {'Python': 'Guido van Rossum', ... 'Perl': 'Larry Wall', ...
'Tcl': 'John Ousterhout' } >>> >>> language = 'Python' >>> creator = table[language] >>> creator 'Guido van Rossum' ``` `>>> for lang in table:` _# Same as: for lang in table.keys()_ ``` ...
print(lang, '\t', table[lang]) ... Tcl John Ousterhout Python Guido van Rossum Perl Larry Wall ``` The last command uses a for loop, which we haven’t covered in detail yet.
If you aren’t familiar with for loops, this command simply iterates through each key in the table and prints a tab-separated list of keys and their values.
We’ll learn more about for loops in Chapter 13. Dictionaries aren’t sequences like lists and strings, but if you need to step through the items in a dictionary, it’s easy—calling the dictionary keys method returns all stored **|** ----- keys, which you can iterate through with a for.
If needed, you can index from key to value inside the for loop, as was done in this code. In fact, Python also lets you step through a dictionary’s keys list without actually calling the keys method in most for loops.
For any dictionary D, saying for key in D: works the same as saying the complete for key in D.keys():.
This is really just another instance of the iterators mentioned earlier, which allow the in membership operator to work on dictionaries as well (more on iterators later in this book). ###### Dictionary Usage Notes Dictionaries are fairly straightforward tools once you get the hang of them, but here are a few addition...
Dictionaries are mappings, not sequences; because there’s no notion of ordering among their items, things like concatenation (an ordered joining) and slicing (extracting a contiguous section) simply don’t apply.
In fact, Python raises an error when your code runs if you try to do such things. - Assigning to new indexes adds entries.
Keys can be created when you write a dictionary literal (in which case they are embedded in the literal itself), or when you assign values to new keys of an existing dictionary object.
The end result is the same. - Keys need not always be strings. Our examples so far have used strings as keys, but any other immutable objects (i.e., not lists) work just as well.
For instance, you can use integers as keys, which makes the dictionary look much like a list (when indexing, at least).
Tuples are sometimes used as dictionary keys too, allowing for compound key values.
Class instance objects (discussed in Part VI) can also be used as keys, as long as they have the proper protocol methods; roughly, they need to tell Python that their values are hashable and won’t change, as otherwise they would be useless as fixed keys. ###### Using dictionaries to simulate flexible lists The last p...
By using integer keys, dictionaries can emulate lists that seem to grow on offset assignment: **|** ----- ``` >>> D = {} >>> D[99] = 'spam' >>> D[99] 'spam' >>> D {99: 'spam'} ``` Here, it looks as if D is a 100-item list, but it’s really a dictionary with a single entry; the value of the key 99 is the...
You can access this structure with offsets much like a list, but you don’t have to allocate space for all the positions you might ever need to assign values to in the future.
When used like this, dictionaries are like more flexible equivalents of lists. ###### Using dictionaries for sparse data structures In a similar way, dictionary keys are also commonly leveraged to implement sparse data structures—for example, multidimensional arrays where only a few positions have values stored in th...
The keys are tuples that record the coordinates of nonempty slots. Rather than allocating a large and mostly empty threedimensional matrix to hold these values, we can use a simple two-item dictionary.
In this scheme, accessing an empty slot triggers a nonexistent key exception, as these slots are not physically stored: ``` >>> Matrix[(2,3,6)] Traceback (most recent call last): File "<stdin>", line 1, in ? KeyError: (2, 3, 6) ###### Avoiding missing-key errors ``` Errors for nonexistent key fetches are com...
There are at least three ways to fill in a default value instead of getting such an error message—you can test for keys ahead of time in `if statements, use a` `try statement to catch and recover from the exception` explicitly, or simply use the dictionary get method shown earlier to provide a default for keys that do ...
print(Matrix[(2,3,6)])` _# See Chapter 12 for if/else_ **|** ----- ``` ... else: ... print(0) ... 0 >>> try: ``` `... print(Matrix[(2,3,6)])` _# Try to index_ `...
except KeyError:` _# Catch and recover_ `...
print(0)` _# See Chapter 33 for try/except_ ``` ... 0 ``` `>>> Matrix.get((2,3,4), 0)` _# Exists; fetch and return_ ``` 88 ``` `>>> Matrix.get((2,3,6), 0)` _# Doesn't exist; use default arg_ ``` 0 ``` Of these, the get method is the most concise in terms of coding requirements; we’ll study the if and try sta...
In general, they can replace search data structures (because indexing by key is a search operation) and can represent many types of structured information.
For example, dictionaries are one of many ways to describe the properties of an item in your program’s domain; that is, they can serve the same role as “records” or “structs” in other languages. The following, for example, fills out a dictionary by assigning to new keys over time: ``` >>> rec = {} >>> rec['name'] ...
This example again uses a dictionary to capture object properties, but it codes it all at once (rather than assigning to each key separately) and nests a list and a dictionary to represent structured property values: ``` >>> mel = {'name': 'Mark', ...
'jobs': ['trainer', 'writer'], ... 'web': 'www.rmi.net/˜lutz', ...
'home': {'state': 'CO', 'zip':80513}} ``` To fetch components of nested objects, simply string together indexing operations: ``` >>> mel['name'] 'Mark' >>> mel['jobs'] ['trainer', 'writer'] >>> mel['jobs'][1] 'writer' ``` **|** ----- ``` >>> mel['home']['zip'] 80513 ``` Although we’ll learn in Par...
For instance, Python’s interface to DBM access-by-key files looks much like a dictionary that must be opened.
Strings are stored and fetched using key indexes: ``` import anydbm file = anydbm.open("filename") # Link to file file['key'] = 'data' # Store data by key data = file['key'] # Fetch data by key ``` In Chapter 27, you’ll see that you can store entire Python objects this way, too, if you repla...
For Internet work, Python’s CGI script support also presents a dictionary-like interface.
A call to cgi.FieldStorage yields a dictionary-like object with one entry per input field on the client’s web page: ``` import cgi form = cgi.FieldStorage() # Parse form data if 'name' in form: showReply('Hello, ' + form['name'].value) ``` All of these, like dictionaries, are instances of mappings.
Once you learn dictionary interfaces, you’ll find that they apply to a variety of built-in tools in Python. ###### Other Ways to Make Dictionaries Finally, note that because dictionaries are so useful, more ways to build them have emerged over time.
In Python 2.3 and later, for example, the last two calls to the dict constructor (really, type name) shown here have the same effect as the literal and keyassignment forms above them: ``` {'name': 'mel', 'age': 45} # Traditional literal expression D = {} # Assign by keys dynamically D['name'...
As suggested previously in Table 8-2, the last form in the listing is also commonly used in conjunction with the zip function, to combine separate lists of keys and values obtained dynamically at runtime (parsed out of a data file’s columns, for instance).
More on this option in the next section. Provided all the key’s values are the same initially, you can also create a dictionary with this special form—simply pass in a list of keys and an initial value for all of the values (the default is None): ``` >>> dict.fromkeys(['a', 'b'], 0) {'a': 0, 'b': 0} ``` Although ...
However, there is yet another way to create dictionaries, available only in Python 3.0 (and later): the dictionary comprehension expression.
To see how this last form looks, we need to move on to the next section. ###### Dictionary Changes in Python 3.0 This chapter has so far focused on dictionary basics that span releases, but the dictionary’s functionality has mutated in Python 3.0.
If you are using Python 2.X code, you may come across some dictionary tools that either behave differently or are missing altogether in 3.0.
Moreover, 3.0 coders have access to additional dictionary tools not available in 2.X.
Specifically, dictionaries in 3.0: - Support a new dictionary comprehension expression, a close cousin to list and set comprehensions - Return iterable views instead of lists for the methods D.keys, D.values, and D.items - Require new coding styles for scanning by sorted keys, because of the prior point - No lo...
Like the set comprehensions we met in Chapter 5, dictionary comprehensions are available only in 3.0 (not in 2.6).
Like the longstanding list comprehensions we met briefly in Chapter 4 and earlier in this chapter, they run an implied loop, collecting the key/value results of expressions on each iteration and using them to fill out a new dictionary.