12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

108 Chapter 11. Dictionarieselse:inv[val].append(key)return invEach time through the loop, key gets a key from d and val gets the corresponding value. If valis not in inv, that means we haven’t seen it before, so we create a new item and initialize it with asingleton (a list that contains a single element). Otherwise we have seen this value before, so weappend thecorresponding key tothe list.Here isanexample:>>> hist = histogram('parrot')>>> print hist{'a': 1, 'p': 1, 'r': 2, 't': 1, 'o': 1}>>> inv = invert_dict(hist)>>> print inv{1: ['a', 'p', 't', 'o'], 2: ['r']}And here isadiagram showinghistandinv:dictdictlisthist’a’ 1inv10’a’’p’11’p’’r’ 22 ’t’’t’13’o’’o’ 1list2 0’r’A dictionary is represented as a box with the type dict above it and the key-value pairs inside. Ifthe values are integers, floats or strings, I usually draw them inside the box, but I usually draw listsoutside thebox, justtokeep thediagram simple.Lists can be values in a dictionary, as this example shows, but they cannot be keys. Here’s whathappens ifyou try:>>> t = [1, 2, 3]>>> d = dict()>>> d[t] = 'oops'Traceback (most recent call last):File "", line 1, in ?TypeError: list objects are unhashableI mentioned earlier that a dictionary is implemented using a hashtable and that means that the keyshave tobe hashable.A hash is a function that takes a value (of any kind) and returns an integer. Dictionaries use theseintegers, called hashvalues, tostoreand look up key-value pairs.This system works fine if the keys are immutable. But if the keys are mutable, like lists, bad thingshappen. For example, when you create a key-value pair, <strong>Python</strong> hashes the key and stores it in the

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!