"""Python dictionaries http://openbookproject.net/thinkcs/python/english2e/ch12.html """ # a dictionary is a collection of key-value pairs that allows access # to the value by key # create an empty dictionary eng2sp = {} eng2sp['one'] = 'uno' eng2sp['two'] = 'dos' # why is this useful? how would you implement something like this using # a list? print eng2sp # you can create a dictionary by providing key-value pairs in the same # format as the output of the above output: eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'} # order doesn't matter! inventory = {'apples': 430, 'bananas': 312, 'oranges': 525, 'pears': 217} print inventory # the len function returns the number of key-value pairs print len(inventory) # We can change the values in a dictionary: inventory['pears'] = 0 # and delete key-value pairs: del inventory['pears'] # you can determine if a dictionary has an entry with a given key: print 'pears' in inventory print 'bananas' in inventory # you can use integers, strings and tuples as keys: pair_dictionary = {} pair_dictionary[('a', 1)] = 1 pair_dictionary[('z', 3)] = 5 # note that all keys of a dictionary are immutable # you can iterate over a dictionary using a for loop: for key in inventory : print inventory[key] # examples where this is useful: def count_letters(s) : counts = {} for char in s : if not(char in counts) : counts[char] = 0 counts[char] += 1 return counts