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.

120 Chapter 12. Tuplesfor key, val in d.items():print val, keyThe output of thisloop is:0 a2 c1 bAgain.It is common to use tuples as keys in dictionaries (primarily because you can’t use lists). For example,a telephone directory might map from last-name, first-name pairs to telephone numbers.Assuming that wehave definedlast,firstandnumber,wecould write:directory[last,first] = numberThe expression inbrackets isatuple. Wecould usetuple assignment totraversethisdictionary.for last, first in directory:print first, last, directory[last,first]This loop traverses the keys in directory, which are tuples. It assigns the elements of each tupletolastandfirst,then prints thename and corresponding telephone number.There are two ways to represent tuples in a state diagram. The more detailed version shows theindices and elements just as they appear in a list. For example, the tuple ('Cleese', 'John')would appear:tuple01’Cleese’’John’But in a larger diagram you might want to leave out the details. For example, a diagram of thetelephone directorymight appear:dict(’Cleese’, ’John’) ’08700 100 222’(’Chapman’, ’Graham’)(’Idle’, ’Eric’)(’Gilliam’, ’Terry’)(’Jones’, ’Terry’)’08700 100 222’’08700 100 222’’08700 100 222’’08700 100 222’(’Palin’, ’Michael’) ’08700 100 222’Here thetuples are shown using<strong>Python</strong> syntax as agraphical shorthand.The telephone number inthediagram isthecomplaints linefor theBBC, soplease don’t call it.

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

Saved successfully!

Ooh no, something went wrong!