Text stringlengths 1 9.41k |
|---|
A loop variable allows the comprehension to use loop
iteration values along the way.
For example, a standard way to initialize a dictionary dynamically in both 2.6 and 3.0
is to zip together its keys and values and pass the result to the dict call. |
As we’ll learn
in more detail in Chapter 13, the zip function is a way to construct a dictionary from
key and value lists in a single call. |
If you cannot predict the set of keys and values in
your code, you can always build them up as lists and zip them together:
`>>> list(zip(['a', 'b', 'c'], [1, 2, 3]))` _# Zip together keys and values_
```
[('a', 1), ('b', 2), ('c', 3)]
```
`>>> D = dict(zip(['a', 'b', 'c'], [1, 2, 3]))` _# Make a dict from zip resu... |
The following builds a new dictionary with a key/value pair for every such
pair in the zip result (it reads almost the same in Python, but with a bit more formality):
`C:\misc> c:\python30\python` _# Use a dict comprehension_
```
>>> D = {k: v for (k, v) in zip(['a', 'b', 'c'], [1, 2, 3])}
>>> D
{'a': 1, 'c': 3,... |
Unfortunately, to truly understand dictionary comprehensions, we need to also know more about iteration statements and
concepts in Python, and we don’t yet have enough information to address that story
well. |
We’ll learn much more about all flavors of comprehensions (list, set, and dictionary) in Chapters 14 and 20, so we’ll defer further details until later. |
We’ll also study
the zip built-in we used in this section in more detail in Chapter 13, when we explore
```
for loops.
###### Dictionary views
```
In 3.0 the dictionary keys, values, and items methods all return view objects, whereas
in 2.6 they return actual result lists. |
View objects are iterables, which simply means
objects that generate result items one at a time, instead of producing the result list all
at once in memory. |
Besides being iterable, dictionary views also retain the original order
of dictionary components, reflect future changes to the dictionary, and may support
set operations. |
On the other hand, they are not lists, and they do not support operations
like indexing or the list sort method; nor do they display their items when printed.
We’ll discuss the notion of iterables more formally in Chapter 14, but for our purposes
here it’s enough to know that we have to run the results of these three ... |
Given that sets behave much like valueless dictionaries (and are
even coded in curly braces like dictionaries in 3.0), this is a logical symmetry. |
Like
dictionary keys, set items are unordered, unique, and immutable.
Here is what keys lists look like when used in set operations. |
In set operations, views
may be mixed with other views, sets, and dictionaries (dictionaries are treated the same
as their keys views in this context):
`>>> K | {'x': 4}` _# Keys (and some items) views are set-like_
```
{'a', 'x', 'c'}
>>> V & {'x': 4}
TypeError: unsupported operand type(s) for &: 'dict_values' ... |
Now, let’s look at three
other quick coding notes for 3.0 dictionaries.
**|**
-----
###### Sorting dictionary keys
First of all, because keys does not return a list, the traditional coding pattern for scanning a dictionary by sorted keys in 2.X won’t work in 3.0. |
You must either convert to
a list manually or use the sorted call introduced in Chapter 4 and earlier in this chapter
on either a keys view or the dictionary itself:
```
>>> D = {'a':1, 'b':2, 'c':3}
>>> D
{'a': 1, 'c': 3, 'b': 2}
```
`>>> Ks = D.keys()` _# Sorting a view object doesn't work!_
```
>>> Ks.sort(... |
# sorted() returns its result
a 1
b 2
c 3
>>> D
{'a': 1, 'c': 3, 'b': 2} # Better yet, sort the dict directly
```
`>>> for k in sorted(D): print(k, D[k])` _# dict iterators return keys_
```
...
a 1
b 2
c 3
###### Dictionary magnitude comparisons no longer work
```
Secondly, while in Pytho... |
However, it can be
simulated by comparing sorted keys lists manually:
```
sorted(D1.items()) < sorted(D2.items()) # Like 2.6 D1 < D2
```
Dictionary equality tests still work in 3.0, though. |
Since we’ll revisit this in the next
chapter in the context of comparisons at large, we’ll defer further details here.
**|**
-----
###### The has_key method is dead: long live in!
Finally, the widely used dictionary has_key key presence test method is gone in 3.0.
Instead, use the in membership expression, or a ge... |
The dictionary
type is similar, but it stores items by key instead of by position and does not maintain
any reliable left-to-right order among its items. |
Both lists and dictionaries are mutable,
and so support a variety of in-place change operations not available for strings: for
example, lists can be grown by append calls, and dictionaries by assignment to new keys.
In the next chapter, we will wrap up our in-depth core object type tour by looking at
tuples and files. |
After that, we’ll move on to statements that code the logic that processes
our objects, taking us another step toward writing complete programs. |
Before we tackle
those topics, though, here are some chapter quiz questions to review.
**|**
-----
###### Test Your Knowledge: Quiz
1. |
Name two ways to build a list containing five integer zeros.
2. Name two ways to build a dictionary with two keys, 'a' and 'b', each having an
associated value of 0.
3. |
Name four operations that change a list object in-place.
4. Name four operations that change a dictionary object in-place.
###### Test Your Knowledge: Answers
1. |
A literal expression like [0, 0, 0, 0, 0] and a repetition expression like [0] * 5
will each create a list of five zeros. |
In practice, you might also build one up with a
loop that starts with an empty list and appends 0 to it in each iteration:
```
L.append(0). |
A list comprehension ([0 for i in range(5)]) could work here, too,
```
but this is more work than you need to do.
2. |
A literal expression such as {'a': 0, 'b': 0} or a series of assignments like D = {},
```
D['a'] = 0, and D['b'] = 0 would create the desired dictionary. |
You can also use
```
the newer and simpler-to-code dict(a=0, b=0) keyword form, or the more flexible
```
dict([('a', 0), ('b', 0)]) key/value sequences form. |
Or, because all the values
```
are the same, you can use the special form dict.fromkeys('ab', 0). In 3.0, you can
also use a dictionary comprehension: {k:0 for k in 'ab'}.
3. |
The append and extend methods grow a list in-place, the sort and reverse methods
order and reverse lists, the insert method inserts an item at an offset, the remove
and `pop methods delete from a list by value and by position, the` `del statement`
deletes an item or slice, and index and slice assignment statements repl... |
Pick any four of these for the quiz.
4. Dictionaries are primarily changed by assignment to a new or existing key, which
creates or changes the key’s entry in the table. |
Also, the del statement deletes a
key’s entry, the dictionary update method merges one dictionary into another inplace, and D.pop(key) removes a key and returns the value it had. |
Dictionaries also
have other, more exotic in-place change methods not listed in this chapter, such
as setdefault; see reference sources for more details.
**|**
-----
###### CHAPTER 9
### Tuples, Files, and Everything Else
This chapter rounds out our in-depth look at the core object types in Python by exploring the... |
As you’ll see, the tuple is a relatively simple
object that largely performs operations you’ve already learned about for strings and
lists. |
The file object is a commonly used and full-featured tool for processing files; the
basic overview of files here is supplemented by larger examples in later chapters.
This chapter also concludes this part of the book by looking at properties common to
all the core object types we’ve met—the notions of equality, compar... |
We’ll also briefly explore other object types in the Python toolbox; as
you’ll see, although we’ve covered all the primary built-in types, the object story in
Python is broader than I’ve implied thus far. |
Finally, we’ll close this part of the book
by taking a look at a set of common object type pitfalls and exploring some exercises
that will allow you to experiment with the ideas you’ve learned.
###### Tuples
The last collection type in our survey is the Python tuple. |
Tuples construct simple
groups of objects. |
They work exactly like lists, except that tuples can’t be changed inplace (they’re immutable) and are usually written as a series of items in parentheses,
not square brackets. |
Although they don’t support as many methods, tuples share most
of their properties with lists. Here’s a quick look at the basics. |
Tuples are:
_Ordered collections of arbitrary objects_
Like strings and lists, tuples are positionally ordered collections of objects (i.e.,
they maintain a left-to-right order among their contents); like lists, they can embed
any kind of object.
_Accessed by offset_
Like strings and lists, items in a tuple are access... |
However, like strings, tuples are immutable; they don’t support any of the
in-place change operations applied to lists.
_Fixed-length, heterogeneous, and arbitrarily nestable_
Because tuples are immutable, you cannot change the size of a tuple without making a copy. |
On the other hand, tuples can hold any type of object, including other
compound objects (e.g., lists, dictionaries, other tuples), and so support arbitrary
nesting.
_Arrays of object references_
Like lists, tuples are best thought of as object reference arrays; tuples store access
points to other objects (references), ... |
A tuple is written as a series of objects
(technically, expressions that generate objects), separated by commas and normally
enclosed in parentheses. |
An empty tuple is just a parentheses pair with nothing inside.
_Table 9-1. |
Common tuple literals and operations_
**Operation** **Interpretation**
`()` An empty tuple
`T = (0,)` A one-item tuple (not an expression)
`T = (0, 'Ni', 1.2, 3)` A four-item tuple
`T = 0, 'Ni', 1.2, 3` Another four-item tuple (same as prior line)
`T = ('abc', ('def', 'ghi'))` Nested tuples
`T = tuple('spam')`... |
Notice in Table 9-1 that tuples do not have all the methods that lists have (e.g., an append call won’t
work here). |
They do, however, support the usual sequence operations that we saw for
both strings and lists:
`>>> (1, 2) + (3, 4)` _# Concatenation_
```
(1, 2, 3, 4)
```
`>>> (1, 2) * 4` _# Repetition_
```
(1, 2, 1, 2, 1, 2, 1, 2)
```
`>>> T = (1, 2, 3, 4)` _# Indexing, slicing_
```
>>> T[0], T[1:3]
(1, (2, 3))
###### T... |
Because
parentheses can also enclose expressions (see Chapter 5), you need to do something
special to tell Python when a single object in parentheses is a tuple object and not a
simple expression. |
If you really want a single-item tuple, simply add a trailing comma
after the single item, before the closing parenthesis:
`>>> x = (40)` _# An integer!_
```
>>> x
40
```
`>>> y = (40,)` _# A tuple containing an integer_
```
>>> y
(40,)
```
As a special case, Python also allows you to omit the opening and cl... |
For instance, the
fourth line of Table 9-1 simply lists four items separated by commas. |
In the context of
an assignment statement, Python recognizes this as a tuple, even though it doesn’t have
parentheses.
Now, some people will tell you to always use parentheses in your tuples, and some will
tell you to never use parentheses in tuples (and still others have lives, and won’t tell
you what to do with your... |
The only significant places where the parentheses
are required are when a tuple is passed as a literal in a function call (where parentheses
matter), and when one is listed in a Python 2.X print statement (where commas are
significant).
For beginners, the best advice is that it’s probably easier to use the parentheses... |
Many programmers (myself included) also find
that parentheses tend to aid script readability by making the tuples more explicit, but
your mileage may vary.
**|**
-----
###### Conversions, methods, and immutability
Apart from literal syntax differences, tuple operations (the middle rows in Table 9-1)
are identical ... |
The only differences worth noting are that
the +, *, and slicing operations return new tuples when applied to tuples, and that tuples
don’t provide the same methods you saw for strings, lists, and dictionaries. |
If you want
to sort a tuple, for example, you’ll usually have to either first convert it to a list to gain
access to a sorting method call and make it a mutable object, or use the newer sorted
built-in that accepts any sequence object (and more):
```
>>> T = ('cc', 'aa', 'dd', 'bb')
```
`>>> tmp = list(T)` _# Make a... |
The following, for example,
makes a list from a tuple, adding 20 to each item along the way:
```
>>> T = (1, 2, 3, 4, 5)
>>> L = [x + 20 for x in T]
>>> L
[21, 22, 23, 24, 25]
```
List comprehensions are really sequence operations—they always build new lists, but
they may be used to iterate over any sequence o... |
As we’ll see later in the book, they even work on some things that are not
physically stored sequences—any iterable objects will do, including files, which are
automatically read line by line.
Although tuples don’t have the same methods as lists and strings, they do have two of
their own as of Python 2.6 and 3.0—index... |
A list inside a tuple, for instance, can be changed as usual:
```
>>> T = (1, [2, 3], 4)
```
`>>> T[1] = 'spam'` _# This fails: can't change tuple itself_
```
TypeError: object doesn't support item assignment
```
`>>> T[1][0] = 'spam'` _# This works: can change mutables inside_
```
>>> T
(1, ['spam', 3], 4)
... |
Which, coincidentally, brings us to the next section.
###### Why Lists and Tuples?
This seems to be the first question that always comes up when teaching beginners about
tuples: why do we need tuples if we have lists? |
Some of the reasoning may be historic;
Python’s creator is a mathematician by training, and he has been quoted as seeing a
tuple as a simple association of objects and a list as a data structure that changes over
time. |
In fact, this use of the word “tuple” derives from mathematics, as does its frequent
use for a row in a relational database table.
The best answer, however, seems to be that the immutability of tuples provides some
_integrity—you can be sure a tuple won’t be changed through another reference else-_
where in a program,... |
Tuples, therefore, serve a
similar role to “constant” declarations in other languages, though the notion of
constantness is associated with objects in Python, not variables.
Tuples can also be used in places that lists cannot—for example, as dictionary keys
(see the sparse matrix example in Chapter 8). |
Some built-in operations may also require
or imply tuples, not lists, though such operations have often been generalized in recent
years. |
As a rule of thumb, lists are the tool of choice for ordered collections that might
need to change; tuples can handle the other cases of fixed associations.
###### Files
You may already be familiar with the notion of files, which are named storage compartments on your computer that are managed by your operating syste... |
The last major
built-in object type that we’ll examine on our object types tour provides a way to access
those files inside Python programs.
**|**
-----
In short, the built-in open function creates a Python file object, which serves as a link
to a file residing on your machine. |
After calling open, you can transfer strings of data
to and from the associated external file by calling the returned file object’s methods.
Compared to the types you’ve seen so far, file objects are somewhat unusual. |
They’re
not numbers, sequences, or mappings, and they don’t respond to expression operators;
they export only methods for common file-processing tasks. |
Most file methods are
concerned with performing input from and output to the external file associated with
a file object, but other file methods allow us to seek to a new position in the file, flush
output buffers, and so on. |
Table 9-2 summarizes common file operations.
_Table 9-2. |
Common file operations_
**Operation** **Interpretation**
`output = open(r'C:\spam', 'w')` Create output file ('w' means write)
`input = open('data', 'r')` Create input file ('r' means read)
`input = open('data')` Same as prior line ('r' is the default)
`aString = input.read()` Read entire file into a single stri... |
The mode is typically the string 'r' to open for
text input (the default), `'w' to create and open for text output, or` `'a' to open for`
appending text to the end. |
The processing mode argument can specify additional
options:
- Adding a b to the mode string allows for binary data (end-of-line translations and
3.0 Unicode encodings are turned off).
**|**
-----
- Adding a + opens the file for both input and output (i.e., you can both read and
write to the same file object, of... |
The external
filename argument may include a platform-specific and absolute or relative directory
path prefix; without a directory path, the file is assumed to exist in the current working
directory (i.e., where the script runs). |
We’ll cover file fundamentals and explore some
basic examples here, but we won’t go into all file-processing mode options; as usual,
consult the Python library manual for additional details.
###### Using Files
Once you make a file object with open, you can call its methods to read from or write
to the associated exte... |
In all cases, file text takes the form of strings in Python
programs; reading a file returns its text in strings, and text is passed to the write methods
as strings. |
Reading and writing methods come in multiple flavors; Table 9-2 lists the
most common. |
Here are a few fundamental usage notes:
_File iterators are best for reading lines_
Though the reading and writing methods in the table are common, keep in mind
that probably the best way to read lines from a text file today is to not read the file
at all—as we’ll see in Chapter 14, files also have an iterator that au... |
Similarly, unlike with the print operation, Python does not
add any formatting and does not convert objects to strings automatically when you
write data to a file—you must send an already formatted string. |
Because of this,
the tools we have already met to convert objects to and from strings (e.g., `int,`
```
float, str, and the string formatting expression and method) come in handy when
```
dealing with files. |
Python also includes advanced standard library tools for handling generic object storage (such as the `pickle module) and for dealing with`
packed binary data in files (such as the struct module). |
We’ll see both of these at
work later in this chapter.
```
close is usually optional
```
Calling the file close method terminates your connection to the external file. |
As
discussed in Chapter 6, in Python an object’s memory space is automatically reclaimed as soon as the object is no longer referenced anywhere in the program.
When file objects are reclaimed, Python also automatically closes the files if they
are still open (this also happens when a program shuts down). |
This means you
**|**
-----
don’t always need to manually close your files, especially in simple scripts that
don’t run for long. |
On the other hand, including manual close calls can’t hurt and
is usually a good idea in larger systems. |
Also, strictly speaking, this auto-close-oncollection feature of files is not part of the language definition, and it may change
over time. |
Consequently, manually issuing file close method calls is a good habit
to form. |
(For an alternative way to guarantee automatic file closes, also see this
section’s later discussion of the file object’s context manager, used with the new
```
with/as statement in Python 2.6 and 3.0.)
```
_Files are buffered and seekable._
The prior paragraph’s notes about closing files are important, because clos... |
By default, output
files are always buffered, which means that text you write may not be transferred
from memory to disk immediately—closing a file, or running its flush method,
forces the buffered data to disk. |
You can avoid buffering with extra open arguments,
but it may impede performance. |
Python files are also random-access on a byte offset
basis—their seek method allows your scripts to jump around to read and write at
specific locations.
###### Files in Action
Let’s work through a simple example that demonstrates file-processing basics. |
The
following code begins by opening a new text file for output, writing two lines (strings
terminated with a newline marker, \n), and closing the file. |
Later, the example opens
the same file again in input mode and reads the lines back one at a time with
```
readline. |
Notice that the third readline call returns an empty string; this is how Python
```
file methods tell you that you’ve reached the end of the file (empty lines in the file come
back as strings containing just a newline character, not as empty strings). |
Here’s the
complete interaction:
`>>> myfile = open('myfile.txt', 'w')` _# Open for text output: create/empty_
`>>> myfile.write('hello text file\n')` _# Write a line of text: string_
```
16
>>> myfile.write('goodbye text file\n')
18
```
`>>> myfile.close()` _# Flush output buffers to disk_
`>>> myfile = open(... |
This example
writes each line of text, including its end-of-line terminator, `\n, as a string; write`
**|**
-----
methods don’t add the end-of-line character for us, so we must include it to properly
terminate our lines (otherwise the next write will simply extend the current line in the
file).
If you want to disp... |
print(line, end='')
...
hello text file
goodbye text file
```
When coded this way, the temporary file object created by open will automatically read
and return one line on each loop iteration. |
This form is usually easiest to code, good
on memory use, and may be faster than some other options (depending on many variables, of course). |
Since we haven’t reached statements or iterators yet, though, you’ll
have to wait until Chapter 14 for a more complete explanation of this code.
###### Text and binary files in Python 3.0
Strictly speaking, the example in the prior section uses text files. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.