#!/usr/bin/python """ dictionaries.py -- sample uses of dictionaries Jeff Ondich, 24 October 2006 Python's "dictionaries" are associative arrays (like Perl's "hashes"). You can think of them as arrays whose indices can be (almost) any object, not just integers starting at 0. Dictionaries are also referred to as "mapping types" in some of the Python documentation. """ # Initialize a dictionary. theDictionary = { 'goat' : 'domestic', 'moose' : 'wild', 'kudu' : 'wild', 'emu' : 'weird' } # It's cool that you can print a dictionary so easily. print theDictionary # Iterating over the (key, value) pairs in a dictionary is a snap. for key in theDictionary: print '%s => %s' % (key, theDictionary[key]) print # Iterate over the keys in alphabetical order. print theDictionary.keys() sortedKeys = theDictionary.keys() sortedKeys.sort() # sort() sorts in place, and does not return the sorted list for key in sortedKeys: print '%s => %s' % (key, theDictionary[key]) print # Test for the presence of a given key using "in". animal = raw_input('Animal, please: ') if animal in theDictionary: print 'The %s is %s' % (animal, theDictionary[animal]) else: print 'The %s is not in the dictionary' % animal # Delete a (key, value) pair via the key. del theDictionary['kudu'] print theDictionary # Go to http://docs.python.org/lib/typesmapping.html and experiment with some of the # operations described there.