49
5.2 – Dictionaries
5.2a - Introduction
Dictionaries are a type of data structure that
are a
little like lists in that they are a sequence of elements. However,
elements are not accessed using indexes as are lists, but using keys. Each element in a dictionary consists of a key/value
pair separated by a colon. For example “george”:”blue”. The string “george” is the key and “blue” is the value. Keys can be
other datatypes, for example numbers. However, the datatype of all keys in a dictionary must be the same.
Because elements are retrieved using their keys looking them up is done in just one go. This means it is a very fast
operation which takes the same time no matter whether the dictionary has 1 or 1 million elements.
5.2b - An Example
# Note the use of curly brackets at the start and end of the dictionary, and
colons to separate the key/value pairs.
logins = {“john”:”yellow”, “paul”:”red”, “george”:”blue”, “ringo”:”green”}
print(logins[“george”]) => “blue”
And
# Change george’s password to purple
logins[“george”] = “purple”
print(logins)
Gives
{“ringo”: “green”, “paul”: “red”, “john”: “yellow”, “george”: “purple”}
Note how the order of the dictionary has changed. It is not possible to stipulate the order in a dictionary, but this does
not matter as sequential access it not needed because element values are accessed using keys.
5.2c - Iteration
Dictionaries can be iterated over using a for loop like so:
# Print all the keys
for item in logins:
print(item)
# Print all the values
for item in logins:
print(logins[item])
# Print both
for key, value in logins.items():
print(“The key is:”, key, “and the value is:”, value)
Prints:
The key is: ringo and the value is: green
The key is: paul and the value is: red
The key is: john and the value is: yellow
The key is: george and the value is: blue
There are many methods and functions associated with dictionaries. Look at the official Python documentation. Also,
values stored in a dictionary can be virtually any data type. For example, athletes and their list of running times as values.
Note that samantha has one less time than mary.
training_times = {“mary”:[12, 45.23, 32.21], “samantha”:[ 11.5, 40.1]}
AN INTRODUCTION TO PYTHON!
!
OCR GCSE COMPUTING
PAGE 26 OF 41!
!
MARK CLARKSON, 2012