Home arrow Python arrow Page 6 - Python 101 (part 4): Feeding The Snake

Of Keys And Locks - Python

Luke Skywalker has the Force. Python programmers havedictionaries and tuples. What's the connection? Read on to find out...

TABLE OF CONTENTS:
  1. Python 101 (part 4): Feeding The Snake
  2. Running The Lights
  3. Strange Food
  4. Unbreakable
  5. Looking Up The Dictionary
  6. Of Keys And Locks
By: Vikram Vaswani, (c) Melonfire
Rating: starstarstarstarstar / 8
June 25, 2001

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement
Two of the most important and useful methods associated with Python dictionaries are the keys() and values() methods, used to return a list of the keys and values stored in a dictionary respectively. The next example should make this clearer:

>>> characters {'princess': 'Leia', 'teacher': 'Obi-Wan', 'new hope': 'Luke', 'bad guy': 'Darth'} >>> characters.keys() ['princess', 'teacher', 'new hope', 'bad guy'] >>> characters.values() ['Leia', 'Obi-Wan', 'Luke', 'Darth'] >>>
Since dictionaries do not use numeric indices, it would not normally be possible to iterate through a dictionary using a "for" loop. However, since both keys() and values() return a list (which *is* compatible with "for"), they can come in extremely handy. Take a look at the following Python program, which sets up a dictionary mapping years to director names, and then iterates through the dictionary with a "for" loop.

#!/usr/bin/python # define a dictionary directors = {1995:"Mel Gibson", 1996:"Anthony Minghella", 1997:"James Cameron", 1998:"Steven Spielberg", 1999:"Sam Mendes", 2000:"Steven Soderbergh"} # loop through for x in directors.keys(): print "And the Oscar for Best Director in", x, "goes to", directors[x]
Here's the output.

And the Oscar for Best Director in 1999 goes to Sam Mendes And the Oscar for Best Director in 1998 goes to Steven Spielberg And the Oscar for Best Director in 1997 goes to James Cameron And the Oscar for Best Director in 1996 goes to Anthony Minghella And the Oscar for Best Director in 1995 goes to Mel Gibson And the Oscar for Best Director in 2000 goes to Steven Soderbergh
In case you'd like it in chronological order, you can always use the sort() function on the list.

#!/usr/bin/python # define a dictionary directors = {1995:"Mel Gibson", 1996:"Anthony Minghella", 1997:"James Cameron", 1998:"Steven Spielberg", 1999:"Sam Mendes", 2000:"Steven Soderbergh"} # get and sort the list years = directors.keys() years.sort() # loop through for x in years: print "And the Oscar for Best Director in", x, "goes to", directors[x]
In this case, I've first obtained a list of keys, sort()ed them, and then used the sorted list in the "for" loop.

As opposed to keys() and values(), the items() method returns something a little more complex - a list of tuples, each tuple containing a key-value pair from the dictionary. It's actually quite elegant - take a look!

>>> characters {'princess': 'Leia', 'teacher': 'Obi-Wan', 'new hope': 'Luke', 'bad guy': 'Darth'} >>> characters.items() [('princess', 'Leia'), ('teacher', 'Obi-Wan'), ('new hope', 'Luke'), ('bad guy', 'Darth')] >>>
And that's about it for today. While this article was not as code-intensive as the previous ones (hey, even you need a break!), we've nevertheless broken a lot of new ground. You now know about two of Python's more unusual data structures, the tuple and the dictionary, have a fair idea of the capabilities and features of each, and will be able to impress your friends with your exhaustive knowledge of Best Director Oscar-winners.

In the next article, we'll be moving away from built-in Python data structures to something a little more interesting: interacting with files on the system. Python can be used to read data from, and write data to, files on your filesystem - and I'll be giving you all the gory details next time. Make sure you come back for that!

 
 
>>> More Python Articles          >>> More By Vikram Vaswani, (c) Melonfire
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PYTHON ARTICLES

- 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: