Dictionaries in Python

A Python dictionary is an important structure for dealing with data. One reason is that a dictionary is more properly an advanced structure that is imple­mented in terms of more basic ones. A list, for example, is a collection of things (integers, reals, or strings) that is accessed by using an index, where the index is an integer. If the integer is given, the contents of the list at that location can be retrieved or modified.

A dictionary allows a more complex, expensive, and useful indexing scheme: it is accessed by content (or rather, a description of content). A dictionary can be indexed by a string, which in general would be referred to as a key, and the infor­mation at that location in the dictionary is said to be associated with that key. For example, let’s assume we have a dictionary that returns the value of a color given the name. A color, as described in Chapter 7, is specified by a red, green, and blue component. A tuple such as (100,200,100) can be used to represent a color. In a dictionary named colors, the value of colors[‘red’] is (255,0,0) and color s[‘blue’] is (0,0,255). Naturally, it is important to know what names are possible or the index used will not be legal and will cause an error. colors[‘copper’] may result in an index error, which is called a KeyError for a dictionary.

The Python syntax for setting up a dictionary differs from anything that has been seen before. The dictionary colors could be created in this way:

colors = {‘red’:(255, 0, 0),   ‘blue’:(0,0,255),


The braces { … } enclose all of the things being defined as part of the dic­tionary. Each entry is a pair, with a key followed by a “:” followed by a data ele­ment. The pair red:(255,0,0) means that the key “red” is associated with the value (255,0,0) in this dictionary.

Now, the name colors looks like a list, but it is indexed by a string:

print (colors[‘blue’])

The index is called a key when referring to a dictionary. That’s because it is not really an index, in that the string cannot directly address a location. Instead, the key is searched for, and if it is a legal key (i.e., it has been defined), the cor­responding data element is selected. The definition of colors creates a list of keys and a list of data.

When the expression colors[‘blue’] is seen, the key “blue” is searched for in the list of all keys. It is found at location 1, so the result of the expression is the data element at 1, which is (0,0,255).

New associations can be made in assignment statements:

colors[‘khaki’] = (240,230,140)

A dictionary can be created with an empty pair of braces and then have val­ues given using assignments:

colors = {}

colors[‘red’] = (255, 0, 0)

As with other variables, the value of an element in a dictionary can be changed. This changes the association with the key; there can only be one item associated with a key. The assignment

colors[‘red’] = (200.,0,0)

re-assigns the value associated with the key “red.” To delete it altogether, use the del() function:


Other types can be used as keys in a dictionary. In fact, any immutable type can be used. Hence, it is possible to create a dictionary that reverses the associa­tion of name to its RGB color, allowing the color to be used as the key and the name to be retrieved. For example,

names = {}

names[(255,0,0)] = ‘red’

names[(0,255,0)] = ‘green’

This dictionary uses tuples as keys. Lists cannot be used because they are not immutable.

1. Example: A Naive Latin – English Translation

A successful language translation program is difficult to implement. Human languages are unlike computer languages in that they have nuances. Words have more than one meaning, and many words mean essentially the same thing. Some words mean one thing in a particular context and a different thing in another
context. Sometimes a word can be a noun and a verb. What this program will do is substitute English words for Latin ones, using a Python dictionary as the basis.

A collection of Latin words with their English counterparts has been placed into a text file named “latin.txt.” The file has the Latin word, a space, and the English equivalent on a single line in the file. The program accepts text from the keyboard and translates it into English, word by word, assuming that it originally consisted of Latin words. The file of Latin words has 3,129 items, but it should be understood that one word in any language has many forms depending on how it is used. Many words are missing in one form or another.

The program is simple. The file of words is read in and converted into a dictionary. The file has a Latin word, a comma, and an English word, so a line is read, converted to a tuple using split(), and the Latin word is used as a key to store the English word into the dictionary.

Next, the program asks the user for a phrase in Latin, and the user types it in. The phrase is split into individual words. Each word is looked up in the diction­ary, and the English version is printed. This is the first step in creating a transla­tion program. The code looks like this:

Translation is more complex than just changing words, and that’s all this program does. Still, it is an important step. A favorite Latin phrase from the TV program The West Wing is “Post hoc, ergo propter hoc.” Given this phrase, the program produced

after this therefore because of this.

which is a good translation. The phrase “All dogs go to heaven” was sent to an online translation program, which produced

omnes canes ad caelum ire conspexerit

This program here translates it back into English as:

all dogs to sky go conspexerit

The word “conspexerit” was not successfully translated, so it was left as it was (the online program translates that word as “glance”).

However, the program does not perform well on the Lord’s Prayer:

Pater noster qui es in caelis sanctificetur nomen tuum.

Adveniat regnum tuum.

Fiat voluntas tua sicut in caelo et in terra.

Panem nostrum quotidianum da nobis hodie et dimitte nobis debita nostra sicut et nos dimittimus debitoribus.

Fiat voluntas tua sicut in caelo et in terra.


The above Latin version was turned into the following English translation: father our that you are against heavens holy name your down rule your

becomes last your as against heaven and against earth

bread our daily da us day and dimitte us debita our as and us forgive debtors

becomes last your as in heaven and in earth


A useful addition to the code would be to permit the user to add new words into the dictionary. In particular, it could prompt the user for words that it could not find, and perhaps even ask whether similar words were related to the un­known one, such as “dimittimus” and “dimitte.” (Being able to have a basic un­derstanding of the grammar would be better still.)

2. Functions for Dictionaries

The power of the store-fetch scheme in the dictionary is impressive. There are some methods that apply mainly to dictionaries and that can be useful in more complex programs. The method keys() returns the collection of all of the keys that can be used with a dictionary. So


is a list of all of the keys, and this can be searched before doing any complex operations on the dictionary. The list of keys is not in any specific order, and if they need to be sorted then


will do the job. The del() method has been used to remove specific keys, but diet. clear() removes all of them.

The method setdefault() can establish a default value for a key that has not been defined. When an attempt is made to access a dictionary using a key, an error occurs if the key has not been defined for that dictionary. This method makes the key known so that no error will occur and a value can be returned for it (None, perhaps).

dict.setdefault(key, default=None)

Other useful functions include:

The expression key in dict is True if the key specified exists in the diction­ary dict.

3. Dictionaries and Loops

Dictionaries are intended for random access, but on occasion, it is necessary to scan through parts or all of one. We need to create a list from the pairs in the dictionary and then loop through the list. For example,

for (key,value) in dict.items():

print (key, ” has the value “, value)

The keys are given in an internal order, which is not alphabetical. It is a simple matter to sort them, though:

for (key,value) in sorted(dict.items()):

print (key, ” has the value “, value)

By converting the dictionary pairs in a list, any of the operations on lists can be applied to a dictionary as well. It is even possible to use comprehensions to initialize a dictionary. For example

d = {angle:sin(radians(angle)) for angle in (0,45.,90.,135., 180.)}

creates a dictionary of the sines of some angles indexed by the angle.


Source: Parker James R. (2021), Python: An Introduction to Programming, Mercury Learning and Information; Second edition.

Leave a Reply

Your email address will not be published. Required fields are marked *