12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

As mentioned earlier, because dictionaries are not sequences, they don’t maintainany dependable left-to-right order. This means that if we make a dictionary, andprint it back, its keys may come back in a different order than how we typed them:>>> D = {'a': 1, 'b': 2, 'c': 3}>>> D{'a': 1, 'c': 3, 'b': 2}What do we do, though, if we do need to impose an ordering on a dictionary’sitems? One common solution is to grab a list of keys with the dictionary keysmethod, sort that with the list sort method, and then step through the result with a<strong>Python</strong> for loop:>>> Ks = D.keys( ) # Unordered keys list>>> Ks['a', 'c', 'b']>>> Ks.sort( ) # Sorted keys list>>> Ks['a', 'b', 'c']>>> for key in Ks: # Iterate though sorted keysprint key, '=>', D[key]a => 1b => 2c => 3This is a three-step process, though, as we’ll see in later chapters, in recent versionsof <strong>Python</strong> it can be done in one step with the newer sorted built-in function (sortedreturns the result and sorts a variety of object types):>>> D{'a': 1, 'c': 3, 'b': 2}>>> for key in sorted(D):print key, '=>', D[key]a => 1b => 2c => 3This case serves as an excuse to introduce the <strong>Python</strong> for loop. The for loop is a simpleand efficient way to step through all the items in a sequence and run a block ofcode for each item in turn. A user-defined loop variable (key, here) is used to referencethe current item each time through. The net effect in our example is to print theunordered dictionary’s keys and values, in sorted-key order.The for loop, and its more general cousin the while loop, are the main ways we coderepetitive tasks as statements in our scripts. Really, though, the for loop, like its relativethe list comprehension (which we met earlier) is a sequence operation. It works82 | Chapter 4: Introducing <strong>Python</strong> Object Types

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!