12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

11.4. Dictionaries and lists 107This function is yet another example of the search pattern, but it uses a feature we haven’t seenbefore, raise. The raise statement causes an exception; in this case it causes a ValueError,which generally indicates that thereissomething wrong withthevalue of aparameter.Ifwegettotheendoftheloop,thatmeansvdoesn’tappearinthedictionaryasavalue,soweraisean exception.Here isanexample of asuccessful reverse lookup:>>> h = histogram('parrot')>>> k = reverse_lookup(h, 2)>>> print krAnd an unsuccessful one:>>> k = reverse_lookup(h, 3)Traceback (most recent call last):File "", line 1, in ?File "", line 5, in reverse_lookupValueErrorThe result when you raise an exception is the same as when <strong>Python</strong> raises one: it prints a tracebackand an errormessage.Theraisestatement takes adetailed error message as anoptional argument. For example:>>> raise ValueError, 'value does not appear in the dictionary'Traceback (most recent call last):File "", line 1, in ?ValueError: value does not appear in the dictionaryAreverselookupismuchslowerthanaforwardlookup;ifyouhavetodoitoften,orifthedictionarygets big, the performance of your program will suffer.Exercise11.4 Modifyreverse_lookupsothatitbuildsandreturnsalistofallkeysthatmaptov,or an empty listifthere arenone.11.4 Dictionariesand listsLists can appear as values in a dictionary. For example, if you were given a dictionary that mapsfrom letters to frequencies, you might want to invert it; that is, create a dictionary that maps fromfrequenciestoletters. Sincetheremightbeseveralletterswiththesamefrequency,eachvalueintheinverted dictionary should bealistof letters.Here isafunction that inverts adictionary:def invert_dict(d):inv = dict()for key in d:val = d[key]if val not in inv:inv[val] = [key]

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

Saved successfully!

Ooh no, something went wrong!