Python Programming: An Introduction to Computer Science

(Nora) #1
11.6. NON-SEQUENTIALCOLLECTIONS 193

Noticeespeciallytheveryendoftheprogram.To runtheapplication,wecreateaninstanceoftheCalculator
classandthencallitsrunmethod.


11.6 Non-SequentialCollections.


Pythonprovidesanotherbuilt-indatatypeforcollections,calledadictionary. Whiledictionariesareincred-
iblyuseful,they arenotascommoninotherlanguagesaslists(arrays).Theexampleprogramsintherestof
thebookwillnotusedictionaries,soyoucanskiptherestofthissectionif you’ve learnedallyouwantto
aboutcollectionsforthemoment.


11.6.1 DictionaryBasics.


Listsallow ustostoreandretrieve itemsfromsequentialcollections.Whenwewanttoaccessaniteminthe
collection,welookit upbyindex—itspositioninthecollection.Many applicationsrequirea moreflexible
waytolookupinformation.Forexample,wemightwanttoretrieve informationabouta studentoremployee
basedontheirsocialsecuritynumber. Inprogrammingterminology, thisis akey-valuepair. We accessthe
value(studentinformation)associatedwitha particularkey (socialsecuritynumber).If youthinka bit,you
cancomeupwithlotsofotherexamplesofusefulkey-valuepairs:namesandphonenumbers,usernames
andpasswords,zipcodesandshippingcosts,statenamesandcapitals,salesitemsandquantityinstock,etc.
Acollectionthatallowsustolookupinformationassociatedwitharbitrarykeysiscalledamapping.
Pythondictionariesaremappings. Someotherprogramminglanguagesprovidesimilarstructurescalled
hashesorassociativearrays. A dictionarycanbecreatedinPythonbylistingkey-valuepairsinsideofcurly
braces.Hereis a simpledictionarythatstoressomefictionalusernamesandpasswords.





passwd = {"guido":"superprogrammer", "turing":"genius", "bill":"monopoly"}





Noticethatkeysandvaluesarejoinedwitha “:”,andcommasareusedtoseparatethepairs.
Themainusefora dictionaryis to lookupthevalueassociatedwitha particularkey. Thisis donethrough
indexingnotation.





passwd["guido"]
’superprogrammer’
passwd["bill"]
’monopoly’





Ingeneral,


[]

returnstheobjectassociatedwiththegivenkey.
Dictionariesaremutable;thevalueassociatedwitha key canbechangedthroughassignment.





passwd["bill"]= "bluescreen"
passwd
{’turing’: ’genius’,’bill’: ’bluescreen’, ’guido’: ’superprogrammer’}





Inthisexample,youcanseethatthevalueassociatedwith’bill’haschangedto’bluescreen’.
Alsonoticethatthedictionaryprintsoutina differentorderfromhow it wasoriginallycreated.Thisis
nota mistake. Mappingsareinherentlyunordered.Internally, Pythonstoresdictionariesina waythatmakes
key lookupveryefficient.Whena dictionaryis printedout,theorderofkeyswilllookessentiallyrandom.If
youwanttokeepa collectionofitemsina certainorder, youneeda sequence,nota mapping.
To summarize,dictionariesaremutablecollectionsthatimplementa mappingfromkeystovalues.Our
passwordexampleshoweda dictionaryhavingstringsasbothkeysandvalues.Ingeneral,keyscanbeany
immutabletype,andvaluescanbeany typeat all,includingprogrammer-definedclasses.Pythondictionaries
areveryefficientandcanroutinelystoreevenhundredsofthousandsofitems.

Free download pdf