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.

106 Chapter 11. Dictionaries>>> h.get('a', 0)1>>> h.get('b', 0)0Usegettowritehistogrammoreconcisely. You should be able toeliminatetheifstatement.11.2 Looping and dictionariesIf you use a dictionary in a for statement, it traverses the keys of the dictionary. For example,print_histprints each key and thecorresponding value:def print_hist(h):for c in h:print c, h[c]Here’s what theoutput looks like:>>> h = histogram('parrot')>>> print_hist(h)a 1p 1r 2t 1o 1Again, the keys areinno particular order.Exercise 11.3 Dictionaries have a method called keys that returns the keys of the dictionary, in noparticular order,as alist.Modifyprint_histtoprint thekeys and their values inalphabetical order.11.3 ReverselookupGivenadictionarydandakeyk,itiseasytofindthecorrespondingvaluev = d[k]. Thisoperationiscalled alookup.But what if you have v and you want to find k? You have two problems: first, there might be morethanonekeythatmapstothevaluev. Dependingontheapplication,youmightbeabletopickone,or you might have to make a list that contains all of them. Second, there is no simple syntax to do areverse lookup; you have tosearch.Here isafunction that takes avalue and returnsthe firstkey that maps tothat value:def reverse_lookup(d, v):for k in d:if d[k] == v:return kraise ValueError

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

Saved successfully!

Ooh no, something went wrong!