Professional Documents
Culture Documents
Dictionaries
Containers Learned So Far
- List
- A flexible easy to use container for many situations. Mutable, indexed, and maintains the order
of insertion. Not very efficient to modify/search etc.
- Still probably the most common container in Python. Many specialized versions of this data
structure exist in other libraries, eg. the numpy array which is optimized for linear algebra!
Key/value pairs are a recurring thing in programming. Keys are unique identifiers, but values can be
anything!
Dictionary Usage
Let’s say you were hired by a secretive government organization overseeing a
highly classified project, and were tasked with programming an authentication
program in Python. The program should take an identifier, and return a dictionary
with relevant information about the person identified.
Dictionary Usage
# Empty dictionary
agents = {}
# Create an agent
agent = {
'name': 'James Bond',
'clearance': 34,
'agency': 'MI-6'
}
- Most workloads can be achieved using only the data structures described above, however many
more containers exist that are optimized for different things. The collections library contains many
high performance containers that fill very niche rolls, ie the deque, ordered dict, named tuple etc.
Exercise
Download “cities.py” from Blackboard (under this tutorial section’s page). This
python file contains a string containing canadian cities in the format
with each line representing one city. Your task is to parse this string (remember
methods such as “split” for strings), and place the data in a relevant container.
Construct two dictionaries, one with the province as a key and a list of cities and
their land areas as a value (possibly grouped as a tuple), and another with the city
as a key and the province as a value. Which province has the most/least cities?
Which province has the greatest total municipal land area? What province is
Merritt in?