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.

104 Chapter 11. DictionariesTheorderofthekey-valuepairsisnotthesame. Infact,ifyoutypethesameexampleonyourcomputer,youmightgetadifferentresult.Ingeneral,theorderofitemsinadictionaryisunpredictable.Butthat’snotaproblembecausetheelementsofadictionaryareneverindexedwithintegerindices.Instead, you usethekeys tolook up thecorresponding values:>>> print eng2sp['two']'dos'The key’two’always maps tothe value'dos'sotheorder ofthe itemsdoesn’t matter.Ifthekey isn’tinthedictionary, you get an exception:>>> print eng2sp['four']KeyError: 'four'Thelenfunction works ondictionaries; itreturns thenumber of key-value pairs:>>> len(eng2sp)3Theinoperatorworksondictionaries;ittellsyouwhethersomethingappearsasakeyinthedictionary(appearing as avalue isnot good enough).>>> 'one' in eng2spTrue>>> 'uno' in eng2spFalseToseewhethersomethingappearsasavalueinadictionary,youcanusethemethodvalues,whichreturns thevalues as a list,and then usetheinoperator:>>> vals = eng2sp.values()>>> 'uno' in valsTrueThe in operator uses different algorithms for lists and dictionaries. For lists, it uses a searchalgorithm, as in Section 8.6. As the list gets longer, the search time gets longer in direct proportion.For dictionaries, <strong>Python</strong> uses an algorithm called a hashtable that has a remarkableproperty: the in operator takes about the same amount of time no matter how many items thereare in a dictionary. I won’t explain how that’s possible, but you can read more about it atwikipedia.org/wiki/Hash_table.Exercise 11.1 Write a function that reads the words in words.txt and stores them as keys in adictionary. It doesn’t matter what the values are. Then you can use the in operator as a fast way tocheck whether a stringisinthedictionary.IfyoudidExercise10.8,youcancomparethespeedofthisimplementationwiththelistinoperatorand the bisection search.11.1 DictionaryasasetofcountersSuppose you are given a string and you want to count how many times each letter appears. Thereareseveral ways you could doit:

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

Saved successfully!

Ooh no, something went wrong!