Section 3.6 Dictionary
Just as Python provides the dictionary when we want to have easy access to key-value pairs, Java also provides us a similar mechanism. Rather than the dictionary terminology, Java calls these objects Maps. Java provides two different implementations of a map, one is called the
TreeMap and the other is called a HashMap. As you might guess the TreeMap uses a balanced binary tree behind the scenes, and the HashMap uses a hash table.
Lets stay with a simple frequency counting example, only this time we will count the frequency of words in a document. A simple Python program for this job could look like this:
This program reads the file
alice30.txt (which follows), and it then splits it into a list of words. Next it creates a dictionary called count which maps each word to the number of times that word occurs in the text. Finally, it prints out the words in alphabetical order along with their frequency.
Data: alice30.txtDown, down, down. Would the fall NEVER come to an end! 'I wonder how many miles I've fallen by this time?' she said aloud. 'I must be getting somewhere near the centre of the earth. Let me see: that would be four thousand miles down, I think--' (for, you see, Alice had learnt several things of this sort in her lessons in the schoolroom, and though this was not a VERY good opportunity for showing off her knowledge, as there was no one to listen to her, still it was good practice to say it over) '--yes, that's about the right distance--but then I wonder what Latitude or Longitude I've got to?' (Alice had no idea what Latitude was, or Longitude either, but thought they were nice grand words to say.)
Notice that the structure of the program is very similar to the numeric histogram program.
Improve the program above to remove the punctuation.
You have attempted of activities on this page.
