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. Here's the output. In case you'd like it in chronological order, you can always use the sort() function on the list. 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!
blog comments powered by Disqus |