You are on page 1of 11

Tutorial #7

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!

inventory = ['pickles', 'medpack', 'cards', 'unknown']


last_item = inventory[-1]
Containers Learned So Far
- Tuple
- Very similar to a list, but immutable
- No methods such as insert, append etc.
- Items are read only, entries cannot be re-assigned. Must construct the tuple again from
scratch if this is desired

items = [('eggs', 10), ('oranges', 34), ('apples', 12)]


Containers Learned So Far
- Set
- A unique collection of hashable objects. No indexing, order of insertion is not controlled by
user
- Mutable, but cannot contain any object type unlike the other containers we’ve learned so far
- Can only add items at construction time or by calling “add”
- Several useful methods for constructing subsets, ie intersection, difference, union, symmetric
difference etc.

nums = {-4, -3, 1, 2, 3, 4, -2, -8}


negative_nums = {-3, -1, -4, -9}
nums_subset = nums.intersection(negative_nums)
Dictionaries
- A useful container in which we can use any “hashable” type as the index, i.e.
string, int, float, or even a tuple!
- This allows us to create very meaningful relationships between a container’s
“index” and the object it holds
- Keys are kind of a set, they are unique and can only be hashable types
- Values can be any objects, including other dictionaries!
Declaring a Dictionary
my_first_dictionary = {'Name': 'George',
'Favourite Programming Language': 'Python',
'Age': 27,
32: 'I don\'t know what this key would mean, but it\'s allowed'}

print('What is George\'s favourite programming language?:', my_first_dictionary['Favourite Programming Language'])

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'
}

# Add the agent to the agents dictionary


agents['007'] = agent

# Create another agent


agent = {
'name': 'Jason Bourne',
'clearance': 23,
'agency': 'CIA'
}

# Add the agent to the agents dictionary


agents['Delta One'] = agent

print(agents['Delta One']['name'], 'has clearance level', agents['Delta One']['clearance'])


print(agents['007']['name'], 'has clearance level', agents['007']['clearance'])
Dictionaries
- Dictionaries are very good at storing complex data, and allowing us to look-up
items using a key that is more meaningful than just an integer!
- Faster insertion, searching and deletion than lists, especially for large data
structures
- Faster look-up with lists
Containers Summary
Lists Tuples Sets Dictionaries

Mutable Yes No Yes Yes

Ordered Yes Yes No No

Stores Anything Yes Yes No, must be Keys must be


hashable hashable, but
values can be
anything

- 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

Province, City Name, Land Area

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?

You might also like