194 CHAPTER11. DATA COLLECTIONS
11.6.2 DictionaryOperations
Like lists,Pythondictionariessupporta numberofhandybuilt-inoperations.Youhave alreadyseenhow
dictionariescanbedefinedbyexplicitlylistingthekey-valuepairsincurlybraces.Youcanalsoextenda
dictionarybyaddingnew entries.Supposea new useris addedtoourpasswordsystem.We canexpandthe
dictionarybyassigninga passwordforthenew username.
passwd[’newuser’] = ’ImANewbie’
passwd
{’turing’: ’genius’,’bill’: ’bluescreen’, \
’newuser’: ’ImANewbie’,’guido’: ’superprogrammer’}
Infact,a commonmethodforbuildingdictionariesis tostartwithanemptycollectionandaddthekey-
valuepairsoneata time.Supposethatusernamesandpasswordswerestoredina filecalledpasswords,
whereeachlineofthefilecontainsa usernameandpasswordwitha spacebetween.We couldeasilycreate
thepasswddictionaryfromthefile.
passwd = {}
for line in open(’passwords’,’r’).readlines():
user, pass = string.split(line)
passwd[user] = pass
To manipulatethecontentsofa dictionary, Pythonprovidesthefollowingmethods.
Method Meaning
dict .haskey( key ) Returnstrueif dictionarycontainsthespecifiedkey,
falseif it doesn’t.
dict .keys() Returnsa listofthekeys.
dict .values() Returnsa listofthevalues.
dict .items() Returnsa listoftuples(key,value)representing
thekey-valuepairs.
del dict [ key ] Deletethespecifiedentry.
dict .clear() Deleteallentries.
Thesemethodsaremostlyself-explanatory. Forillustration,hereis aninteractive sessionusingourpass-
worddictionary:
passwd.keys()
[’turing’, ’bill’,’newuser’, ’guido’]
passwd.values()
[’genius’, ’bluescreen’,’ImANewbie’, ’superprogrammer’]
passwd.items()
[(’turing’, ’genius’),(’bill’, ’bluescreen’), (’newuser’, ’ImANewbie’),\
(’guido’, ’superprogrammer’)]
passwd.has_key(’bill’)
1
passwd.has_key(’fred’)
0
passwd.clear()
passwd
{}
11.6.3 ExampleProgram:WordFrequency
Let’s writea programthatanalyzestextdocumentsandcountshowmany timeseachwordappearsinthe
document.Thiskindofanalysisis sometimesusedasa crudemeasureofthestylesimilaritybetweentwo
documentsandis alsousedbyautomaticindexingandarchivingprograms(suchasInternetsearchengines).