As mappings, as we’ve already seen, dictionaries only support accessing items by key. However, they also support type-specific operations with method calls that are useful in a variety of common use cases. As mentioned earlier, because dictionaries are not sequences, they don’t maintain any dependable left-to-right order. This means that if we make a dictionary, and print it back, its keys may come back in a different order than how we typed them: >>> D = {'a': 1, 'b': 2, 'c': 3} What do we do, though, if we do need to impose an ordering on a dictionary’s items? One common solution is to grab a list of keys with the dictionarykeysmethod, sort that with the listsort method, and then step through the result with a Pythonforloop: >>> Ks = D.keys() # Unordered keys list >>> Ks.sort() # Sorted keys list >>> for key in Ks: # Iterate though sorted keys a => 1 This is a three-step process, though, as we’ll see in later chapters, in recent versions of Python it can be done in one step with the newersorted built-in function (sorted returns the result and sorts a variety of object types): >>> D >>> for key in sorted(D): a => 1 This case serves as an excuse to introduce the Pythonforloop. Theforloop is a simple and efficient way to step through all the items in a sequence and run a block of code for each item in turn. A user-defined loop variable (key, here) is used to reference the current item each time through. The net effect in our example is to print the unordered dictionary’s keys and values, in sorted-key order. Theforloop, and its more general cousin thewhileloop, are the main ways we code repetitive tasks as statements in our scripts. Really, though, theforloop, like its relative the list comprehension (which we met earlier) is a sequence operation. It works on any object that is a sequence and, also like the list comprehension, even on some things that are not. Here, for example, it is stepping across the characters in a string, printing the uppercase version of each as it goes: >>> for c in 'spam': S We’ll discuss looping statements further later in the book. Iteration and Optimization If the for loop looks like the list comprehension expression introduced earlier, it should: both are really general iteration tools. In fact, both will work on any object that follows the iteration protocol—an idea introduced recently in Python that essentially means a physically stored sequence in memory, or an object that generates one item at a time in the context of an iteration operation. This is why the sorted call used in the prior section works on the dictionary directly—we don’t have to call thekeysmethod to get a sequence because dictionaries are iterable objects. I’ll have more to say about the iteration protocol later in this book. For now, keep in mind that any list comprehension expression, such as this one, which computes the squares of a list of numbers: >>> squares = [x ** 2 for x in [1, 2, 3, 4, 5]] can always be coded as an equivalentforloop that builds the result list manually by appending as it goes: >>> squares = [] >>> squares The list comprehension, though, will generally run faster (perhaps even twice as fast)—a property that could matter in your programs for large data sets. Having said that, though, I should point out that performance measures are tricky business in Python because it optimizes so much, and can vary from release to release. A major rule of thumb in Python is to code for simplicity and readability first, and worry about performance later, after your program is working, and after you’ve proved that there is a genuine performance concern. More often than not, your code will be quick enough as it is. If you do need to tweak code for performance, though, Python includes tools to help you out, including thetimeandtimeitmodules and theprofilemodule. You’ll find more on these later in this book, and in the Python manuals. Please check back next week for the continuation of this article.
blog comments powered by Disqus |
|
|
|
|
|
|
|