Introductory Programming Fall 2004 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 type" Homework 8 Solutions -------------------- First challenge: modify the program to count the number of times each word appears: for word in t: d[word] = d.get(word, 0) + 1 This is a standard idiom for updating a dictionary. Second challenge: print the 10 most common words def print_most_common(d): # Print the ten most common words in the dictionary. # Make a list of tuples, where each tuple contains # a frequency and a word. Sort them in decreasing # order of frequency and print the first ten. t = [] for key in d: pair = (d[key], key) t.append(pair) t.sort() t.reverse() for i in range(10): print t[i] This code builds a list of tuples and sorts it. Sometimes called the DSU pattern, for "decorate, sort, undecorate"