Press enter to skip the top menu

Python Programming

Dictionaries

NCEA Compatibility

Module: as91883 Develop a computer program

Requirements: modifying data stored in collections (e.g. lists, arrays, dictionaries)

Go to top

Learning Outcomes

On completion of this section you will know the nature of tuples and how to:

Go to top

Introduction

Dictionaries is the third member of the trilogy that includes Lists and Tuples.

Dictionaries are based on key-value pairs. The key and its value are separated by a colon.
"Name":"John"
is an example of a kye-value pair.

In this case "Name" is the key and "John" is the value of that key.

Other examples of key-value pairs are "Age":15 and "Occupation":"Student"

To create a dictionary the key-value pairs are grouped together inside a pair of curly brackets as follows:
{"Name":"John", "Age":15, "Occupation":"Student"}
Notice that the different key-value pairs are separated by commas.

Go to top

A simple Dictionary Example

Below is a very simple example of a dictionary. Line 1 is almost identical to the example we have just met; only the name of the person has changed to "Tom". Also the dictionary itself is assigned to a variable Worker.

To access the values in the dictionary we use the key between square brackets. Thus
Worker["Name"] would give us the value of "Tom". We can get the values of the other keys in the same manner

Listing 1
                        Worker = {"Name":"Tom","Age":15,"Occupation":"Student"}
                        print(Worker["Name"])
                        print(Worker["Age"])
                        print(Worker["Occupation"])
                    

In Listing 1 above lines 2, 3 and 4 display the values of the keys "Name", "Age" and "Occupation".

Fig 1

This running of the program shown in Listing 1 displays the values of the three keys

Listing 2
                        Worker = {"Name":"Tom","Age":15,"Occupation":"Student"}
                        description = f'The person is called {Worker["Name"]} and he is {Worker["Age"]} years old. He is a {Worker["Occupation"]}.'
                        print(description)
                    

Listing 2 above is similar to Listing 1 except that this time the three values are inserted into a formatted string at line 2

Fig 2

In Fig 2 above the values of the three keys displayed using a formatted string.

Go to top

Adding key-value Pairs

Unlike tupils we can add extra key-value pairs to a dictionary. The only restriction is that we can't add duplicate keys. We can however duplicate as many values as we want.

To create a key-value pair we simply create a key and assign a value to it as shown in Listing 3 below.

Listing 3
                        Workers = {"Tom": 88559,"Dick": 28344}
                        print("First printing    ")
                        print(Workers)
                        Workers["Harry"] = 66444
                        print("Harry is added   ")
                        print(Workers)
                        Workers["Anne"] = 245780
                        Workers["Kate"] = 265157
                        Workers["Maggie"] = 256884
                        print("Gender balance    ")
                        print(Workers)
                    

In Listing 3 above we have two key-value pairs with keys of "Tom" and "Dick". It may appear strange to have people's names as keys in a dictionary, especially if you have been using a database. Our example here could be a simple app that allows us to quickly check the phone numbers of people whose names we know.

At line 1 starts with a dictionary containing two key-value pairs At line 4 we add another pair with "Harry" as the key and 66444 as the value.

When we print out the value of Workers at line 6 we see that the value "Harry" has been added.

In a similar manner we add the keys "Anne", "Kate" and "Maggie". Again the output from line 10 demonstrates that those key-value pairs have been added to the dictionary.

Fig 3

Fig 3 above shows that the dictionary Workers has been extend from two key-value pairs to six.

Go to top

Sorting Dictionaries

Strictly speaking dictionaries can't be sorted but we can work our way around the issue. We can sort a dictionary's contents and store the result in another dictionary.

For our sorting example we shall use a variation of the code in Listing 3

Listing 4
                        Workers = {"Tom": 88559,"Dick": 28344}
                        print("First printing    ",Workers)
                        Workers["Harry"] = 66444
                        print("Harry is added   ",Workers)
                        Workers["Anne"] = 245780
                        Workers["Kate"] = 265157
                        Workers["Maggie"] = 256884
                        print("Gender balance    ",Workers)
                        Employees=dict(sorted(Workers.items()))
                        print("Alphabetic sorting",Employees)
                        for name, phone in Employees.items():
                            print(name, phone)
                    

The first eight lines of Listing 4 are straight out of Listing 3 and should therefore be familiar to us.

Line 9 sorts the key-value pairs in Workers and stores the result in the dictionary Employees.. The dictionary itself remains unaltered.

Lines 11 and 12 introduce a neat version of the for loop. Instead of the normal one variable, it has two variables: one for the key and one for the values.

It iterates through the key-value pairs in Emplouees storing the key in name and the value in phone. On each iteration line 12 prints the key and the value.

Fig 4

The first four outputs in Fig 4 are from are from the dictionary Workers while the rest are from the sorted dictionary Employees.

Go to top

A simple Payroll Application

Up to now we have been looking at the nature of dictionaries without paying much attention to how they could be actually used. In the following sections we shall look at how we could use dictionaries to store and process payroll data.

We shall start with a very simple example and gradually build and extend that example.

Listing 5
                        Worker = {"Name":"Tom","Rate":36,"Hours":40}
                        hourlyRate = Worker["Rate"]
                        hoursWorked = Worker["Hours"]
                        grossPay = hourlyRate * hoursWorked
                        taxPaid = grossPay * 0.25
                        netPay = grossPay - taxPaid
                        ourPayslip = f'Payslip for {Worker["Name"]}\nHours worked: {hoursWorked}\nHourly rate: {hourlyRate}\n'
                        ourPayslip += f'Gross: {grossPay}\nTax deducted: {taxPaid}\nNet pay: {netPay}'
                        print(ourPayslip)  
                    

Listing 5 above shows our example.

Line 1 consists of a dictionary named Worker. It consists of three key-value pairs: "Name", "Rate" and "Hours" - the most basic payroll data.

Lines 2 and 3 use the "Rate" and "Hours" keys to extract those values and store them in the variables hourlyRate and hoursWorked

Lines 4, 5 and 6 calculate the values of the gross, tax and net and store them in the variables grossPay, taxPaid and netPay.

Lines 7 and 8 build up a formatted string containing of the values of the payroll calculation along with appropriate labels.

Line 9 prints the completed formatted string.

Fig 5

Above we see the output from line 9 of Listing 5.

Go to top

A Dictionary of Dictionaries

In line 1 of Listing 5 we defined a dictionary that consisted of three key-value pairs. This allowed us to process a payroll for for one single employee.

If we had more than one employee then a program like Listing 5 would be of no use to us. Instead we would need a dictionary structure that could contain a number of other dictionaries.

We can't put multiple versions of the dictionary Worker defined in line 1 of Listing 5 into another dictionary because a dictionary can only contain key-value pairs. The way around this is to restructure line 1 of Listing 5 as follows:
Workers = {1111:{"Name":"Tom","Rate":36,"Hours":40}}

By now we have key-value pair with the item 1111 as the key and and the dictionary {"Name":"Tom","Rate":36,"Hours":40} as the value. As a key-value pair they can be added to another dictionary, which is what we have done.

Here we have a dictionary of a dictionary

So far we have aded a key-value pair to the dictionary Workers. Being a dictionary we can add multiple other key-value pairs to it as shown below:
Workers = {
1111:{"Name":"Tom","Rate":36,"Hours":40},
1112:{"Name":"Dick","Rate":45,"Hours":36},
1113:{"Name":"Harry","Rate":42,"Hours":40}
}

Here we have the dictionary Workers which has three key value pairs:

Thus we have a dictionary of dictionaries. Now let us look at how it works.

Listing 6
                        Workers = { 
                            1111:{"Name":"Tom","Rate":36,"Hours":40}, 
                            1112:{"Name":"Dick","Rate":45,"Hours":36}, 
                            1113:{"Name":"Harry","Rate":42,"Hours":40} 
                        } 
                        for employee in Workers: 
                            print(employee)                        
                    

In the first five lines of Listing 6 we have the same dictionary of dictionaries that we studied above spanning lines 1 - 5.

The for loop prints out the contents of the dictionary Workers. The result is shown in Fig 6 below.
Fig 6

Here we see that it only prints the key components of the three key-value pairs of Workers but does not print out their values.

Listing 7
                         Workers = { 
                            1111:{"Name":"Tom","Rate":36,"Hours":40}, 
                            1112:{"Name":"Dick","Rate":45,"Hours":36}, 
                            1113:{"Name":"Harry","Rate":42,"Hours":40} 
                        } 
                        for employee in Workers: 
                            print(employee, Workers[employee])                   
                    

Listing 7 above differes from Listing 6 only by one expression: the second argument to print() in line 6

We have seen above in Listing 6 that iterating over a group of key-value pairs in a dictionary gives us the keys and not the values. To get the values we need to use the key in square brackets after the dictionary name.

In Listing 7, on the first iteration through the loop at line 6 emplouee will have a value of 1111 and thus Workers[employee will be equivalent to Workers[1111]. This will give us the matching value, i.e. the dictionary {"Name":"Tom","Rate":36,"Hours":40}

On the second and third iterations the values for employee will be 1112 and 1112 respectively, thus giving us the second and third disctionaries as appropriate.

Fig 7

Above we see the output from line 7 of Listing 7. The first column are the keys of the three different dictionaries while the dictionaries are the values of the different keys.

Listing 8
                        
                        Workers = {
                            1111:{"Name":"Tom","Rate":36,"Hours":40},
                            1112:{"Name":"Dick","Rate":45,"Hours":36},
                            1113:{"Name":"Harry","Rate":42,"Hours":40}
                        }
                        for employee in Workers:
                            print(f'The key for the record is {employee}\nThe data in the record is {Workers[employee]}')
                    

Listing 8 above is identical to listing 7 except for line 7. Here a formatted string is used to display the data in a more verbose format.

Fig 8

The formatted string breaks the outut in two lines: the first line showing only the key for each key-value pair while the second line shows the corresponding value i.e. the dictionary showing the pay details.

Listing 9
                        Workers = {  
                            1111:{"Name":"Tom","Rate":36,"Hours":40},  
                            1112:{"Name":"Dick","Rate":45,"Hours":36},  
                            1113:{"Name":"Harry","Rate":42,"Hours":40}  
                        }  
                        for employee in Workers:  
                            employeeDetails = Workers[employee]  
                            print(employee, employeeDetails)     
                        
                    

Listing 9 is similar to Listing 7 and Listing 8 except for the fact that an extra variable, employeeDetails has been added.

The sole purpose of this variable is that the value of the three dictionaries can be accessed by a single variable instead of the variable name and the key in square brackets.

Fig 9

Despite introducing the extra variable the output form Listing 9 is identical to the output from Listing 7.

Go to top

A simple Payroll Program

We shall complete this page with two more programs where the last program is an extension of the previous one.

Although much bigger than any of the previous programs there is nothing new introduced that has not been covered either on this page or in previous pages.

Listing 10
                        Workers = { 
                            1111:{"Name":"Tom","Rate":36,"Hours":40}, 
                            1112:{"Name":"Dick","Rate":45,"Hours":36}, 
                            1113:{"Name":"Harry","Rate":42,"Hours":40} 
                        } 
                        for employee in Workers: 
                            employeeDetails = Workers[employee] 
                            hourlyRate = employeeDetails["Rate"] 
                            hoursWorked = employeeDetails["Hours"] 
                            grossPay = hourlyRate * hoursWorked 
                            taxPaid = grossPay * 0.25 
                            netPay = grossPay - taxPaid 
                            ourPayslip = f'Payslip for {employeeDetails["Name"]}\nHours worked: {hoursWorked}\nHourly rate: {hourlyRate}\n' 
                            ourPayslip += f'Gross: {grossPay}\nTax deducted: {taxPaid}\nNet pay: {netPay}\n\n' 
                            print(ourPayslip)                        
                    

Lines 1 - 7 work the same as in the previous examples.

Lines 8 and 9 extract the values of the hours and rate from the appropriate key-value pairs. Using the values for the hours and rate lines 10 - 12 calculate the values of the gross, tax and net.

Line 13 creates a formatted string that displays the employee's name, hours worked and hourly rate, and line 14 appends to that another formatted string that displays the values of the gross, tax and net.

Line 15 prints out the completed formatted string.

Fig 10
Go to top

A more complete Payroll Program

Our example in Listing 10 was neither practical nor realistic. This is because it was only able to process one single payroll for any employee.

Employees usually are paid at regular pay periods. Their hourly rate generally stay constant over a number of pay periods but their hours worked may change for each single pay period.

For each employee then, their name and hourly rate should remain constant but for each pay period the hours worked value may change. This means that each employee will have a set of key-value pairs where the key is the pay period and the value is the hours worked for that pay period.

The modified dictionaries for this extension are shown in Listing 11 below.

Listing 11
                        Workers = { 
                            1111:{"Name":"Tom","Rate":36,"PayData":{1:24,2:45,3:36}}, 
                            1112:{"Name":"Dick","Rate":45,"PayData":{1:36,2:36,3:36}}, 
                            1113:{"Name":"Harry","Rate":42,"PayData":{1:42,2:38,3:41}} 
                        } 
                        for employee in Workers: 
                            employeeDetails = Workers[employee] 
                            employeeName = employeeDetails["Name"] 
                            hourlyRate = employeeDetails["Rate"] 
                            payslip = f'IRD number: {employee} Name: {employeeName}  Hourly Rate {hourlyRate}\n' 
                            hoursData=employeeDetails["PayData"] 
                            for payPeriod, hoursWorked in hoursData.items(): 
                                grossPay = hourlyRate * hoursWorked 
                                taxPaid = grossPay * 0.25 
                                netPay = grossPay - taxPaid 
                                payslip += f'Pay period: {payPeriod}  Hours worked: {hoursWorked} Gross: {grossPay} Tax: {taxPaid} Net: {netPay} \n' 
                            print(payslip)                        
                    

If we compare lines 2 - 4 of Listing 10 with their equivalents in Listing 11 we see that the "Hours" key in Listing 10 has been replaced by the "PayData" key in Listing 11. Also the value of this key is a dictionary.

This dictionary has three key-value pairs. The keys are 1, 2 and 3, indicating the first three pay perioes of the year. The value of each key represents the number of hours worked by the employee during that pay period.

Lines 6 - 10 are identical to their equivalents in prevous examples and so we start with line 11. This the variable hoursData gives us a pointer to the dictionary which is the value of the "PayData" key.

Lines 12 - 16 control the processing of the employee's pay for all of the pay periods provided. The entire block forms the body of a for loop.

Line 12 is the start of the version of the for loop that reads two data items at each iteration. In this case it reads the key and value of each of the key-value items in the dictionary "PayData". This will be the number of the pay period and the hours worked. These of course will be stored in the variables payPeriod and hoursWorked.

Lines 13 - 15 calculate the gross, tax and net and store them in the appropriately named variables.

Line 16 builds a formatted string containing the number of the pay period, the hours worked for that period and the gross, tax and net. This string is appended to the string variable payslip that was initialised at line 10.

Once all the pay periods for the current employee have been processed the loop terminates and control passes to line 17 where the value of payslip is printed.

Fig 11

Above we see the result of running Listing 11.

Go to top

Summary

What are dictionaries?

A dictionary is a set of key-value pairs separated by a comma and enclosed between curly brackets

Nature of dictionaries

  • Dictionaries are stored in memory the same as lists and tuples
  • Dictionaries can have multiple key-value pairs, including none.
  • Once created new key-value pairs can be added to a dictionary by providing a key and a value.
  • The key in any dictionary must be unique
  • The key of a dictionary can be any data type except a list and another dictionary.
  • The value of a key value pair can be of any data type, including another dictionary.
Go to top