Introductory Programming Fall 2004 For next Tuesday: 1) finish homework 8 2) prepare for an evaluation on dictionaries. Dictionaries ------------ Make an empty dictionary: d = {} print d print type(d) Add an entry: d['a'] = 1 print d The string 'a' is a key The integer 1 is a value. Dictionaries map keys onto values. Add another entry: d['b'] = 2 print d Now we can use a key to look up the corresponding value. print d['a'] Add another entry, and then loop through the dictionary: d['c'] = 1 for key in d: print d applying a for loop to a dictionary loops through the keys for key in d print d[key] This loops through the keys, looks up each one, and prints the corresponding values. Notice that the entries in a dictionary are not in any particular order. Dictionary methods ------------------ There are a number of methods you can invoke on dictionaries. Methods are functions that you invoke on objects using dot notation. print d.keys() # prints a list of keys print d.values() # print a list of values print d.items() # print a list of tuples, where each tuple contains # a key-value pair Other dictionary methods and operators are described at: http://www.python.org/doc/current/lib/typesmapping.html Notice that a dictionary is a kind of "mapping types"