Home arrow Python arrow Page 4 - The Dictionary Python Object Type

Sorting Keys: for Loops - Python

In this third part of a four-part series on Python object types, we will wrap up our discussion of lists and introduce you to some remarkable things you can do with dictionaries. This article is excerpted from chapter four of the book Learning Python, Third Edition, written by Mark Lutz (O'Reilly, 2008; ISBN: 0596513984). Copyright © 2008 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.

  1. The Dictionary Python Object Type
  2. Dictionaries
  3. Nesting Revisited
  4. Sorting Keys: for Loops
By: O'Reilly Media
Rating: starstarstarstarstar / 5
January 29, 2009

print this article



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}
>>> D
{'a': 1, 'c': 3, 'b': 2}

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
['a', 'c', 'b']

  >>> Ks.sort()                # Sorted keys list
  >>> Ks
  ['a', 'b', 'c']

  >>> for key in Ks:          # Iterate though sorted keys
print key,
'=>', D[key]

  a => 1
  b => 2
  c => 3

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
  {'a': 1, 'c': 3, 'b': 2}

  >>> for key in sorted(D):
         print key, '=>', D[key]

  a => 1
  b => 2
  c => 3

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':
         print c.upper()


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]]
  >>> squares
  [1, 4, 9, 16, 25]

can always be coded as an equivalentforloop that builds the result list manually by appending as it goes:

  >>> squares = []
  >>> for x in [1, 2, 3,
4, 5]:
                           # This is what a list comp does
squares.append(x ** 2)

  >>> squares
  [1, 4, 9, 16, 25]

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.

>>> More Python Articles          >>> More By O'Reilly Media

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Python Big Data Company Gets DARPA Funding
- Python 32 Now Available
- Final Alpha for Python 3.2 is Released
- Python 3.1: String Formatting
- Python 3.1: Strings and Quotes
- Python 3.1: Programming Basics and Strings
- Tuples and Other Python Object Types
- The Dictionary Python Object Type
- String and List Python Object Types
- Introducing Python Object Types
- Mobile Programming using PyS60: Advanced UI ...
- Nested Functions in Python
- Python Parameters, Functions and Arguments
- Python Statements and Functions
- Statements and Iterators in Python

Developer Shed Affiliates


Dev Shed Tutorial Topics: