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