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.

12.6. Dictionaries and tuples 119If you combine zip, for and tuple assignment, you get a useful idiom for traversing two (or more)sequences at the same time. For example, has_match takes two sequences, t1 and t2, and returnsTrueifthere isanindexisuch thatt1[i] == t2[i]:def has_match(t1, t2):for x, y in zip(t1, t2):if x == y:return Truereturn FalseIfyouneedtotraversetheelementsofasequenceandtheirindices,youcanusethebuilt-infunctionenumerate:for index, element in enumerate('abc'):print index, elementThe output of thisloop is:0 a1 b2 cAgain.12.6 Dictionariesand tuplesDictionarieshaveamethodcalleditemsthatreturnsalistoftuples,whereeachtupleisakey-valuepair 2 .>>> d = {'a':0, 'b':1, 'c':2}>>> t = d.items()>>> print t[('a', 0), ('c', 2), ('b', 1)]As you should expect from adictionary, the itemsareinno particular order.Conversely, you can usealistof tuples toinitializeanew dictionary:>>> t = [('a', 0), ('c', 2), ('b', 1)]>>> d = dict(t)>>> print d{'a': 0, 'c': 2, 'b': 1}Combiningdictwithzipyields aconcise way tocreate adictionary:>>> d = dict(zip('abc', range(3)))>>> print d{'a': 0, 'c': 2, 'b': 1}The dictionary method update also takes a list of tuples and adds them, as key-value pairs, to anexisting dictionary.Combining items, tuple assignment and for, you get the idiom for traversing the keys and valuesof adictionary:2 This behavioris slightly differentin <strong>Python</strong>3.0.

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

Saved successfully!

Ooh no, something went wrong!