Home Lesson-6.4

Lesson-6.3

Dictionaries

Pangrams and Dictionaries

Assume that we wish to compute the following mapping between letters of the English alphabet and numbers from 1 to 26:

LetterNumber
a1
b2
......
z26

Each letter in the alphabet is mapped to a unique number from 1 to 26. In the table given above, the mapping is a simple linear mapping: a is mapped to 1, b to 2 and so on. This mapping can be computed in the most uninteresting and lousy way given below:

Phew! I typed the whole thing out. It took me two dull minutes and I learned nothing new at the end of the exercise. My fingers cursed me for the mechanical key-presses while my eyes chided me for staring at the screen without blinking. Besides, the last letter of the alphabet was quite annoyed at being left alone in the last row with no company, while every other letter got to share line-space with four other letters!

Let us try a round about but interesting way. Consider the following line:

the quick brown fox jumps over the lazy dog

This sentence is called a pangram. A pangram is a sentence that uses all the letters of the alphabet. Does that ring any bell?

Plenty of things to learn from those 14 lines of code. Not all diversions are bad. Now that we have an interesting dictionary in place, let us jump into some methods that are bundled along with dict.

 

Dictionary Methods

We have already seen keys and items. Both these are methods that return a view object over which we can iterate. According to the Python documentation, "a view object provides a dynamic view on the dictionary's entries, which means that when the dictionary changes, the view reflects these changes."

This gives the following output:

Using the list function, both the keys and items views can be converted into lists:

The output is as follows:

keys_list is a list of keys in the dictionary mapping. items_list is a list of tuples, where each tuple is a key-value pair. Another useful method is values. This returns a view on the values:

All three views - keys, items, values - support membership tests:

All three return True. Membership tests for keys can be done in a simpler way:

Note that we dropped the keys method and it still worked! Now, to delete a key from a dictionary, we use the familiar pop method:

If key is a key in a dictionary D, D.pop(key) removes the key key in D and returns the value associated with it. Removing a key naturally removes the value associated with it. Dictionaries are aristocratic data structures: keys are higher up in the hierarchy and values depend on the keys for their existence.