Python: Working with Dictionaries

Tutorial Video

Introduction to Dictionaries

An ordinary dictionary has the form:

Python

A Python Dictionary also follows this form. Let's create a dictionary where the single character string of a primary colour is the key for just the full name of the colour.

Python

We can run this script:

When prompted save the script file as dictionaries.py

Then view this dictionary in the variable explorer:

And we can access the keys by typing in the dictionary name colours and indexing using square brackets with the one letter key string:

Python

'red'
Python

'green'
Python

'blue'

Note unlike a list, we cannot index into a dictionary by use of an index number.

Python

KeyError: 0

We will also get this error for a keyword that isn't found:

Python

KeyError: 'c'

We can however create a new keyword by assigning it to a value. Let's add in the secondary colours:

Python

You'll observe in the variable explorer that the dictionary is updated:

We can add in the remaining secondary colours:

Python

We can see the updated dictionary in the variable explorer:

We can double click it to view the entries:

Let's now add in black:

Python

Each keyword must refer to a unique definition. Note in this case how the keyword 'b' has been reassigned from blue to black and the value blue is now gone.

In this case we can call black 'k' and blue 'b':

Python

This is similar to the dictionary MatPlotLib uses for colour designation.

Creating a Dictionary Assigning a Name to a Hex Value

We can look at a quick practical use of a dictionary. Supposing we want to use the "standard colours" in Microsoft Word in our Python program. It may be difficult to remember the hex values of these colours however we can assign the hex values to a keyword letter which we can remember. In this case we can base the "keyword" or key on the name Microsoft give the colours and the "description" or value will be the hex value.

Microsoft Word Standard Colour Name Hex
Dark Red#c00000
Red#ff0000
Orange#ffbf00
Yellow#ffff00
Light Green#92d050
Dark Green#00b050
Light Blue#00b0f0
Blue#007060
Dark Blue#002060
Purple#6f30a0
Python

We can run this script file:

When prompted for a file name we can save it as dictionarycolours.py

Now we can get the numeric values of the colour darkred by typing in:

Python

'c00000'

Using our Dictionary to Print Coloured Text in the Terminal

To print coloured text on the console we need to install ansicolors to do this, close down Spyder and open up the Anaconda Powershell Prompt:

Type in the following command.

Python

Then we need to add the perquisite to our code (line 2)

Once the perquisite on line 2 is executed, we may use the function color to specify the foreground using the input argument fg and background using the input argument bg. This will be the input to the print function.

Let's save the updated Python script dictionarycolours

Python

Now let's create a separate script file which will import all from dictionarycolours (which in turn will import the function color from ansicolour).

We can use the function print, to print to the console. To change the colour of the text in the console we can embed the function color() within a print() statement and the input arguments for color will be the text we wish to print as a string and the input arguments fg and bg standing for foreground and background respectively:

We can specify these colours as hex values:

Python

When we run this script, once again we will be asked for a script name.

Let's call it printtoconsoleincolour.py

And we get:

In this case we have manually input our hex value and as mentioned it can be cumbersome to remember the hex values, so we can instead use our dictionary to specify the colour.

Python

We can however repeat it by using our dictionary to select the hex value for us:

Python

Numeric Dictionary

So far we have only created a dictionary of words. We can also create a dictionary using other datatypes such as integers and numbers. For example, we can make a dictionary which has integer index values and as a result will act very similarly to a list:

Python

We can then index very similarly to a list:

Python

'#00b0f0'

Or alternatively a list of telephone numbers associated with someones name:

Python
Python

1004

Boolean Dictionary

Recall each key has to be unique so you would only have two keys if you used Booleans as keys however multiple keys can have the same definition. Think of it as akin to two words having the same meaning.

Python

Did Camille pass test 1?

Python

False

Dictionary of Lists

It is possible for a dictionary to point to a list. We may for instance instead of using the hex values instead use the [R,G,B] values to individually specify the intensity level of the three primary colour channels.

These intensity values are usually 8 bit meaning 2**8=256 levels. Because we zero order index, one of the levels is 0 so the range is from between 0 to 255 for each colour channel. Some libraries such as MatPlotLib use normalised floats as [R,G,B] values (divide through by 255) but the ansicolor library uses integer [R,G,B] values.

Note the hex form is equivalent except we use hexadecimal notation to specify 16 characters (0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f). Hex has the form '#RRGGBB' and roughly we can think '#ff0000' as f*f=16*16 for the red channel which is the maximum value 256 and we subtract 1 due to zero order indexing.

Microsoft Word Standard Colour NameRGB values
Dark Red[192,0,0]
Red[255,0,0]
Orange[255,192,0]
Yellow[255,255,0]
Light Green[146,208,80]
Dark Green[0,176,80]
Light Blue[0,176,240]
Blue[0,112,96]
Dark Blue[0,32,96]
Purple[112,48,160]
Python

We can run this script and save it as dictionarycolours2

Now we can modify printtoconsoleincolour to load dictionarycolour2 opposed to dictionarycolour

Python

When ran it will input the vector of [R,G,B] values which the function will recognise and print out the coloured message in the console.

Dictionary of Differing DataTypes

So far we have kept all the datatypes in the keys as the same and all the datatypes of the values the same. Like a list it is also possible for each value in a dictionary to have a different data type. For example:

Python

Advertisements