Guidance for the item(s) below:
So far, we have learned how to use Python lists to store sequences of objects. This week we move onto another slightly more complex data structure called dictionary which can store a collection of key-value pairs.
A dictionary (python type: dict
) is a collection of many values that can be indexed by any object type, unlike lists that are automatically indexed by integers. Indexes for dictionaries are called keys, and a key with its associated value is called a key-value pair. Python dictionaries use the curly braces notation { key1: value1, key2: value2, ...}
.
A list containing names of animals ['cat', 'dog', 'hen', 'fish']
Index | Value |
---|---|
0 | 'cat' |
1 | 'dog' |
2 | 'hen' |
3 | 'fish' |
A dictionary containing ages of three people {'john': 12, 'sara': 14.5, 'colin': 13}
. john
-12
is a key-value pair.
Key | Value |
---|---|
'john' | 12 |
'sara' | 14.5 |
'colin' | 13 |
A dictionary containing details of a person {'name': 'john', 'age': 14.5, 'sex': 'F', 'citizen': True}
Key | Value |
---|---|
'name' | 'john' |
'age' | 14.5 |
'gender' | 'F' |
'citizen' | True |
Some examples of defining dictionaries.
friends = {} # empty dictionary
grades = {'TEE3201': 'A'}
numbers = {1: 'one', 2: 'two', 3: 'three'}
is_nice = {'jane': False, 'hakim': True, 'ravi': True}
prices = {'bread': 3.5, 'butter': 5.0, 'banana': 0.15}
Unlike lists, you cannot force a key-value pair in a dictionary to be at a specific position. The order of insertion will be the order of items in a dict.
You can use keys to access values in a dictionary.
Some examples of retrieving values based on the key:
| → |
|
Examples of adding, updating, and deleting dictionary entries:
grades = {'TEE3201': 'A'}
grades['CS2103'] = 'B'
print('After adding:',grades)
grades['TEE3201'] = 'A+'
print('After updating:',grades)
del grades['CS2103']
print('After deleting:', grades)
After adding: {'TEE3201': 'A', 'CS2103': 'B'}
After updating: {'TEE3201': 'A+', 'CS2103': 'B'}
After deleting: {'TEE3201': 'A+'}
Trying to access a value for a non-existent key raises a KeyError
exception.
This example raises an exception because the key 'santa'
does not exist in the dictionary is_nice
:
| → |
|
You can use keys()
and values()
methods to iterate through keys and values of a dictionary, respectively.
The code below shows how to iterate through keys/values of a dictionary.
| → |
|
| → |
|
You can use the sorted()
function to sort the keys/values before iterating through them.
The code below shows how to iterate through keys/values of a dictionary.
| → |
|
As usual, you can use in
and not in
to check whether a key or a value is in a dictionary.
The code below shows how to check if a certain key or a value exists in a dictionary.
| → |
|
| → |
|
Dictionaries and lists can be nested in each other to create more complicated data structures.
This dictionary keeps track of assignments of each subject. Note how the value is a list
rather than a simple value such as an int
or a string
.
assignments = {'TEE3201': ['do exercises', 'submit project'],
'CS2103': [],
'CS3281': ['do presentation']}
Python ignores line breaks and indentations in the middle of a dictionary/list definition which allows you to structure the code into a more readable format (e.g., one key-value pair per line).
As the values in this dictionary are lists, you can do list operations on them, e.g., append()
, len()
print('CS3281 assignments:', assignments['CS3281'])
assignments['CS3281'].append('study for exams')
print(assignments['CS3281'])
print('How many things to do in TEE3201?', len(assignments['TEE3201']))
# calculate total assignments
total = 0
for a in assignments.values():
total = total + len(a)
print('total tasks to do:', total)
CS3281 assignments: ['do presentation']
['do presentation', 'study for exams']
How many things to do in TEE3201? 2
total tasks to do: 4
This dictionary uses dictionaries as values (i.e., nesting dictionaries inside dictionaries). It stores details of a group of persons.
friends = {'john': {'name': 'John Doe', 'birthday': 'Jan 12'},
'sara': {'name': 'Sara Parker', 'birthday': 'Jun 30'},
'betty': {'name': 'Betsy Sims', 'birthday': 'Jan 12'}}
print(friends['john']['birthday'])
# print friends whose birthday is Jan 12
for f in friends.keys():
details = friends[f]
if details['birthday'] == 'Jan 12':
print(details['name'])
Jan 12
John Doe
Betsy Sims
As friends['john']
evaluates to a dictionary, you can use the ['birthday']
notation to find the birthday of that person.
friends['john']['birthday']
→ {'name': 'John Doe', 'birthday': 'Jan 12'}['birthday']
→ 'Jan 12'