NCEA Compatibility
Module: as91883 Develop a computer program
Requirements: modifying data stored in collections (e.g. lists, arrays, dictionaries)
Go to topModule: as91883 Develop a computer program
Requirements: modifying data stored in collections (e.g. lists, arrays, dictionaries)
Go to topOn completion of this section you will know the nature of dictionaries and how to use them in a program.
Go to topDictionaries form the third group 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.
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. ThusWorker["Name"]
would give us the value of "Tom". We can get the values of the other keys in the same manner
In Listing 1 above lines 2, 3 and 4 display the values of the keys "Name", "Age" and "Occupation".
This running of the program shown in Listing 1 displays the values of the three keys
Listing 2 above is similar to Listing 1 except that this time the three values are inserted into a formatted string at line 2
In Fig 2 above the values of the three keys displayed using a formatted string.
Go to topUnlike tuples 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.
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 above shows that the dictionary Workers has been extend from two key-value pairs to six.
Go to topStrictly 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
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 Employees storing the key in name and the value in phone. On each iteration line 12 prints the key and the value.
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 topListing 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.
Above we see the output from line 9 of Listing 5.
Go to topIn 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 added 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.
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.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 above differs 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 employee 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 dictionaries as appropriate.
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 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.
The formatted string breaks the output 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 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.
Despite introducing the extra variable the output form Listing 9 is identical to the output from Listing 7.
Go to topWe 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.
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.
Go to topOur 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.
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 periods 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 previous 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.
Above we see the result of running Listing 11.
Go to topA dictionary is a set of key-value pairs separated by a comma and enclosed between curly brackets. They 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. In dictionaries each key value must be unique, similar to a key field in a database table.
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