8: Dictionaries#
What are dictionaries and why should we care about them?#
Dictionaries are for associating data and quick lookup.
Motivating example: I am making an index for a book, because I want to know which concepts show up on which pages, to make it easier to jump back to the right spots.
1# how to know which chapters talk about strings? or debugging?
2book = [
3 "Chapter 1: talks about strings and how they have the property of immutability also some basic debugging",
4 "Chapter 2: continues talking about advanced methods for strings and also introduces the concept of functions",
5 "Chapter 3: discusses iteration and lists and also debugging",
6]
Here’s what it might look like without dictionaries.
1concepts = ['strings', 'debugging', 'immutability']
2index = []
3
4for entry in book:
5 # split into elements based on the colon
6 elements = entry.split(":")
7 # first element is the chapter
8 chapter = elements[0]
9 # second element is the text
10 text = elements[1]
11
12 # parse the text
13 words = text.split()
14 for keyconcept in concepts:
15 if keyconcept in words:
16 index.append([keyconcept, chapter])
17index
[['strings', 'Chapter 1'],
['debugging', 'Chapter 1'],
['immutability', 'Chapter 1'],
['strings', 'Chapter 2'],
['debugging', 'Chapter 3']]
1# given this data structure, how to find
2# all the chapters that have strings in them?
3query = "strings"
4results = []
5# go through every item in the index
6for item in index:
7 concept, chapter = item
8 # if the concept matches the query
9 if query == concept:
10 results.append(chapter)
11
12print(results)
['Chapter 1', 'Chapter 2']
And here is what it might look like with dictionaries.
1# now consider if the concept index is in a dictionary (much more like what you might see in a book!)
2index_d = {
3 'strings': ['Chapter 1', 'Chapter 2'],
4 'debugging': ['Chapter 1', 'Chapter 3']
5}
1# given this data structure, how to find
2# all the chapters that have strings in them?
3query = "strings"
4index_d.get(query)
['Chapter 1', 'Chapter 2']
Another common use case: attributes of data entries. For instance, attributes of a class, like credit hours, pre-reqs, instructor, location, hours, and so on.
1# without dictionaries
2courses = [
3 ["INST126", 3, "no", "Chan", "hybrid", "MWF"],
4 ["INST256", 4, "yes", "Rony", "in-person", "TR"]
5]
6
7# look up INST126 and check whether it has prereqs
8for course in courses:
9 if course[0] == "INST126":
10 print(course[2])
no
Rather than trying to remember which position we happened to have decided to use to store a particular attribute (if we used lists), we can use semantically meaningful indices for values, i.e., keys! (Don’t worry about the details of this code yet: we’ll build up to it in this chapter.)
1# with dictionaries
2courses = {
3 "INST126": {
4 "credit hours": 3, "prereqs": "no", "instructor": "Chan", "location": "hybrid", "hours": "MWF"
5 },
6 "INST256": {
7 "credit hours": 4, "prereqs": "yes", "instructor": "Rony", "location": "in-person", "hours": "TR"
8 },
9}
10
11# look up INST126 and check whether it has prereqs
12courses.get("INST126").get("prereqs")
'no'
It’s a lot easier to remember keys (if we name them useful things) compared to just indices. And Python can help us remember too!
We’ll come back to both of these examples throughout the chapter: the course catalog as we learn the basics (and nested dictionaries), and the book index when we learn how to build dictionaries from data.
If you’re interested, there are also formal technical reasons to prefer dictionaries over lists if you care about speed/efficiency and your computational task is checking if an item exists in a collection and you’re dealing with very large scale data. The short version: looking up a key in a dictionary is O(1) (constant time: just 1 operation, no matter how big the dictionary is), while checking if an item is in a list is O(n) (grows with the size of the list: even though computers are pretty fast, when you get to quite large database sizes, you’ll notice a difference!). See https://www.geeksforgeeks.org/python/difference-between-list-and-dictionary-in-python/ for a beginner-friendly explanation, or https://wiki.python.org/moin/TimeComplexity for the official reference.
In the future, you may learn the pandas library (and the dataframe data structure, which is sort of a hybrid of lists and dictionaries): you can do really fast lookup, but also sort stuff!
Working with dictionaries: basics#
Let’s start simple. We’ll make a course catalog that maps course codes to course titles, and use it to learn the basic operations. (Later in the chapter, we’ll grow it into the more detailed catalog you saw above.)
Anatomy of a dictionary#
Dictionaries are not so different from… our dictionaries in real life. :) They basically map a bunch of keys (e.g., a word) to corresponding values (e.g., a definition). Another example is indices in the back of print books that map key terms to pages where that term shows up, or tags on websites, that map tags to webpages that include those tags.
Here’s our catalog:
1catalog = {
2 "INST126": "Intro to Programming",
3 "INST201": "Intro to Information Science",
4 "INST326": "Object-Oriented Programming"
5}
6catalog
{'INST126': 'Intro to Programming',
'INST201': 'Intro to Information Science',
'INST326': 'Object-Oriented Programming'}
The key parts of a dictionary literal are:
The
{ }curly braces, which tell you and Python that it’s a dictionary (similar to""for strings, or[]for lists)At least one entry (but usually several), that maps a value on the right of a
:(which works a bit like=in an assignment) to a key on the left. For example, the first entry in our catalog maps the value “Intro to Programming” to the key “INST126”.Similar to lists, we include
,to separate multiple entries in the dictionary.
Style note: the indentation inside the dictionary is more for readability. Python doesn’t care, as long as there are commas between the dictionary entries.
You can also write it out like this, but I find it harder to read:
1catalog = {"INST126": "Intro to Programming", "INST201": "Intro to Information Science", "INST326": "Object-Oriented Programming"}
2catalog
{'INST126': 'Intro to Programming',
'INST201': 'Intro to Information Science',
'INST326': 'Object-Oriented Programming'}
Create a dictionary#
The most direct way to create a dictionary is to type it out, like we just did. You can also start with an empty dictionary, and then add stuff later, programmatically or with other functions.
1empty_catalog = {} # dictionary with nothing in it
2empty_catalog = dict() # same thing
3print(empty_catalog)
4len(empty_catalog)
{}
0
Keys and values don’t have to be typed out directly. You can use variables too! This comes in handy when you’re writing functions that make dictionaries (you’ll do a bunch of this in the PCE!).
1code = "INST314"
2title = "Statistics for Information Science"
3new_catalog = {code: title} # the VALUE of code ("INST314") becomes the key, not the word "code"
4new_catalog
{'INST314': 'Statistics for Information Science'}
PRACTICE: make a dictionary rooms that maps each course to its room: INST126:HBK0302, INST201:ESJ0202, INST326:TYD2102
1# your code here
Answer:
1rooms = {
2 "INST126": "HBK0302",
3 "INST201": "ESJ0202",
4 "INST326": "TYD2102"
5}
Get the value associated with a key#
1catalog = {
2 "INST126": "Intro to Programming",
3 "INST201": "Intro to Information Science",
4 "INST326": "Object-Oriented Programming"
5}
6catalog["INST126"] # put a key inside square brackets associated with a dictionary
'Intro to Programming'
This is the indexing style. It looks a lot like getting things out of a list, except we put a key in the square brackets instead of a position.
1catalog.get("INST126") # use the get method to get the value for the key that we give it
'Intro to Programming'
This is the method style. You call .get() on the dictionary, and give it the key you want to look up. (Python docs for .get())
I tend to prefer the method style, because it’s a bit clearer what’s going on: you can read catalog.get("INST126") as “get the value for INST126 from catalog”. It’s sort of self-documenting!
It also has the advantage of not breaking your program if you try to access a key that doesn’t exist.
1catalog["INST999"] # will crash the program with a KeyError
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
Cell In[15], line 1
----> 1 catalog["INST999"] # will crash the program with a KeyError
KeyError: 'INST999'
.get() lets you specify a default value that should come back if the key doesn’t exist. This is very useful for writing clean and understandable dictionary patterns, such as indexing, which we’ll dig into later in this chapter.
1result = catalog.get("INST999", "Course not found") # will return "Course not found" as the default
2print(result)
Course not found
PRACTICE: how do you get the title for INST326?
1# your code here
Answer:
1catalog.get("INST326") # 'Object-Oriented Programming'
catalog["INST326"] works too!
Adding entries to a dictionary (or updating entries)#
Indexing style, using square brackets and assignment:
1catalog = {
2 "INST126": "Intro to Programming",
3 "INST201": "Intro to Information Science",
4 "INST326": "Object-Oriented Programming"
5}
6print(catalog)
7# add a new course
8catalog["INST314"] = "Statistics for Information Science" # map the title to the key INST314
9print(catalog)
10# rename a course
11catalog["INST326"] = "OO Programming" # INST326 already exists, so we update its title
12print(catalog)
{'INST126': 'Intro to Programming', 'INST201': 'Intro to Information Science', 'INST326': 'Object-Oriented Programming'}
{'INST126': 'Intro to Programming', 'INST201': 'Intro to Information Science', 'INST326': 'Object-Oriented Programming', 'INST314': 'Statistics for Information Science'}
{'INST126': 'Intro to Programming', 'INST201': 'Intro to Information Science', 'INST326': 'OO Programming', 'INST314': 'Statistics for Information Science'}
Notice that adding and updating look exactly the same! If the key isn’t in the dictionary yet, you get a new entry. If it’s already there, you replace its value.
Method style, using .update(). .update() takes another dictionary (that’s why there are curly braces inside the parentheses!), and copies its entries into catalog: adding the ones that are new, and replacing the ones that are already there. (Python docs for .update())
1catalog = {
2 "INST126": "Intro to Programming",
3 "INST201": "Intro to Information Science",
4 "INST326": "Object-Oriented Programming"
5}
6print(catalog)
7# add a new course
8catalog.update({"INST314": "Statistics for Information Science"})
9print(catalog)
10# rename a course
11catalog.update({"INST326": "OO Programming"})
12print(catalog)
{'INST126': 'Intro to Programming', 'INST201': 'Intro to Information Science', 'INST326': 'Object-Oriented Programming'}
{'INST126': 'Intro to Programming', 'INST201': 'Intro to Information Science', 'INST326': 'Object-Oriented Programming', 'INST314': 'Statistics for Information Science'}
{'INST126': 'Intro to Programming', 'INST201': 'Intro to Information Science', 'INST326': 'OO Programming', 'INST314': 'Statistics for Information Science'}
.update() has the advantage of being able to add (or update) multiple entries at once.
1catalog.update({"INST327": "Database Design", "INST201": "Introduction to Information Science"})
2print(catalog)
{'INST126': 'Intro to Programming', 'INST201': 'Introduction to Information Science', 'INST326': 'OO Programming', 'INST314': 'Statistics for Information Science', 'INST327': 'Database Design'}
PRACTICE: how do you add a new course INST346, titled Technologies, Infrastructure and Architecture?
1# your code here
Answer:
1catalog.update({"INST346": "Technologies, Infrastructure and Architecture"})
Or, in the indexing style: catalog["INST346"] = "Technologies, Infrastructure and Architecture"
PRACTICE: how do you rename INST126 to Programming for Information Science?
1# your code here
Answer:
1catalog.update({"INST126": "Programming for Information Science"})
INST126 is already a key, so this updates it, instead of adding a new entry.
PRACTICE: how do you add INST352: Information User Needs and Assessment and INST362: User-Centered Design, in a single operation?
1# your code here
Answer:
1catalog.update({"INST352": "Information User Needs and Assessment", "INST362": "User-Centered Design"})
PRACTICE: how do you rename INST326 back to Object-Oriented Programming, and add INST414: Data Science Techniques, in a single operation?
1# your code here
Answer:
1catalog.update({"INST326": "Object-Oriented Programming", "INST414": "Data Science Techniques"})
One .update() can add and update at the same time.
Building a dictionary in a loop#
Sometimes your data starts out as two lists that line up position by position, e.g., a list of course codes, and a list of course titles. You can build a dictionary out of them with a loop over the positions:
1codes = ["INST126", "INST201", "INST326"]
2titles = ["Intro to Programming", "Intro to Information Science", "Object-Oriented Programming"]
3
4catalog = {} # start with an empty dictionary
5for i in range(len(codes)): # i goes 0, 1, 2: one position for each course
6 code = codes[i] # the course code at position i
7 title = titles[i] # the title at the SAME position i
8 catalog.update({code: title}) # add an entry that maps that code to that title
9catalog
{'INST126': 'Intro to Programming',
'INST201': 'Intro to Information Science',
'INST326': 'Object-Oriented Programming'}
Let’s walk through the first time through the loop. i is 0, so code is codes[0] ("INST126"), and title is titles[0] ("Intro to Programming"). Then catalog.update({"INST126": "Intro to Programming"}) adds that entry to our (empty) catalog. The next time through, i is 1, and we do the same thing for INST201, and so on, until we run out of positions.
This only works if the two lists line up exactly! If they’re out of order, you’ll map titles to the wrong codes, and if one list is shorter, you’ll get an IndexError.
You can use whichever style is comfortable for you. I prefer the method style most of the time: it’s more readable, and .get() doesn’t crash if the key isn’t there. But some things (especially nested dictionaries, which we’ll see below) are more natural with the indexing style, so it’s good to be comfortable with both!
Check if a key is in a dictionary#
“Do we offer INST314?”
1catalog = {
2 "INST126": "Intro to Programming",
3 "INST201": "Intro to Information Science",
4 "INST326": "Object-Oriented Programming"
5}
6print("INST314" in catalog)
False
in checks the keys of a dictionary, not the values. (If you want to check the values, you can do "Intro to Programming" in catalog.values().)
1print("Intro to Programming" in catalog) # False! This is a value, not a key
2print("Intro to Programming" in catalog.values())
False
True
You can also do something similar with .get(): if the key isn’t there, you get the default back. But be careful! If the key is there, you get its value back, not True.
1# retrieve the title for INST314; if it's not found, return "not found"
2catalog.get("INST314", "not found")
'not found'
Doing something different when a key is missing#
Sometimes a default value isn’t enough. If the key isn’t there, you might want your program to do something different, like give a specific message. For that, use in with a conditional, and check for the key before you reach for its value:
1def describe_course(catalog, code):
2 # first, check whether the key is there at all
3 if code not in catalog:
4 # if not, give a message, and stop here
5 return f"Sorry, {code} is not in the catalog"
6 # we only get to this line if the key IS there, so it's safe to look up its value
7 return f"{code} is {catalog.get(code)}"
8
9print(describe_course(catalog, "INST126"))
10print(describe_course(catalog, "INST999"))
INST126 is Intro to Programming
Sorry, INST999 is not in the catalog
Notice the return inside the if. When the code is missing, the function returns its message and stops right there, so it never gets to the line that looks up the value.
I think of .get() with a default as the quick version (I just want some value back, no matter what), and the in check as the careful version (I want to handle the missing key my own way). You’ll use both!
PRACTICE: how do you check if the key “INST326” is in catalog?
1# your code here
Answer:
1"INST326" in catalog # True
List keys and values (and loop through them)#
.keys() gives you all the keys in the dictionary
.values() gives you all the values in the dictionary
.items() gives you all the entries (key-value pairs) in the dictionary. Each entry comes back as a pair, like ('INST126', 'Intro to Programming').
Each of these is iterable. (Python docs for dictionary methods)
1# list all the keys in the dictionary
2catalog.keys()
dict_keys(['INST126', 'INST201', 'INST326'])
1# list all the values in the dictionary
2catalog.values()
dict_values(['Intro to Programming', 'Intro to Information Science', 'Object-Oriented Programming'])
1# list all the key-value pairs in the dictionary
2catalog.items()
dict_items([('INST126', 'Intro to Programming'), ('INST201', 'Intro to Information Science'), ('INST326', 'Object-Oriented Programming')])
This means you can loop through them. For example, here’s how to print the whole catalog:
1# iterate through the keys, and look up each value
2for code in catalog.keys(): # code is "INST126", then "INST201", then "INST326"
3 print(code, catalog.get(code)) # use the key to look up its title
INST126 Intro to Programming
INST201 Intro to Information Science
INST326 Object-Oriented Programming
1# iterate through the items: each item gives you a key AND its value
2for code, title in catalog.items(): # unpack each pair into two variables
3 print(f"{code}: {title}")
INST126: Intro to Programming
INST201: Intro to Information Science
INST326: Object-Oriented Programming
Each item is a pair, and for code, title in ... unpacks it into two variables, the same way name, grade = entry.split(":") unpacks a list of two things. So the first time through the loop, the item is ('INST126', 'Intro to Programming'): code gets 'INST126', and title gets 'Intro to Programming'.
I use the .items() version most of the time, because you get the key and the value in one go, with names that say what they are.
Practice: Code Tracing with Dictionaries#
Predict the output of each code snippet before running the cell!
Trace 1#
1d = {"x": 10, "y": 20, "z": 30}
2print(d["y"])
A)
20B)
"y"C)
10D)
1
Answer:
A) 20
d["y"] retrieves the value associated with the key "y", which is 20.
Trace 2#
1d = {"a": 1, "b": 2}
2d["c"] = 3
3d["a"] = 99
4print(d)
5print(len(d))
A)
{'a': 1, 'b': 2, 'c': 3}then3B)
{'a': 99, 'b': 2, 'c': 3}then3C)
{'a': 99, 'b': 2}then2D)
{'a': 1, 'a': 99, 'b': 2, 'c': 3}then4
Answer:
B) {'a': 99, 'b': 2, 'c': 3} then 3
d["c"] = 3 adds a new entry. d["a"] = 99 updates the existing key "a" (keys are unique — you can’t have two "a" entries). So the dict has 3 entries.
Trace 3#
1d = {"name": "Joel", "age": 30}
2result = d.get("email", "not found")
3print(result)
4print(len(d))
A)
Nonethen2B)
not foundthen2C)
not foundthen3D) KeyError
Answer:
B) not found then 2
"email" is not a key in d, so .get() returns the default value "not found". Importantly, .get() does not add the key to the dictionary — d still has only 2 entries.
Trace 4#
1d = {"a": [1, 2], "b": [3]}
2d["a"].append(3)
3d["c"] = []
4d["c"].append(7)
5print(d)
A)
{'a': [1, 2], 'b': [3], 'c': [7]}B)
{'a': [1, 2, 3], 'b': [3], 'c': [7]}C)
{'a': [3], 'b': [3], 'c': [7]}D)
{'a': [1, 2, 3], 'b': [3], 'c': []}
Answer:
B) {'a': [1, 2, 3], 'b': [3], 'c': [7]}
Dictionary values can be lists (or any other type). d["a"].append(3) gets the list [1, 2] and appends 3 to it — lists are mutable, so this modifies the list in place. d["c"] = [] creates a new key with an empty list, then .append(7) adds to it.
Trace 5#
1d = {"x": 10, "y": 20}
2d.update({"y": 50, "z": 30})
3print(d)
4print("z" in d)
5print(30 in d)
A)
{'x': 10, 'y': 50, 'z': 30}thenTruethenTrueB)
{'x': 10, 'y': 50, 'z': 30}thenTruethenFalseC)
{'x': 10, 'y': 20, 'z': 30}thenTruethenFalseD)
{'x': 10, 'y': 20, 'y': 50, 'z': 30}thenTruethenTrue
Answer:
B) {'x': 10, 'y': 50, 'z': 30} then True then False
.update() adds "z": 30 and updates "y" from 20 to 50. "z" in d checks if "z" is a key → True. 30 in d checks if 30 is a key → False (30 is a value, not a key). The in operator only checks keys!
Practice: Dictionary Scenarios (basics)#
For each scenario, start by creating the dictionary, then complete the retrieval and update operations.
Scenario 1: Gradebook (basic)#
You’re building a simple gradebook that maps student names to their current grade (a single letter grade).
Setup#
Create a dictionary called gradebook with the following entries:
Student |
Grade |
|---|---|
Joel |
B |
Sarah |
A |
Rony |
A+ |
Kacie |
B+ |
Miles |
C |
1# create the gradebook dictionary here
Retrieve#
R1. Print Joel’s grade.
1# your code here
R2. Check if “Pat” is in the gradebook. If so, print their grade; otherwise print "Pat is not in the gradebook".
1# your code here
R3. Use .get() to look up “Zara” in the gradebook. If she’s not there, print "Zara: no grade on file".
1# your code here
Update#
U1. Miles turned in extra credit — update his grade to "B-".
1# your code here
U2. A new student, Pat, joined the class with a grade of "B". Add them to the gradebook.
1# your code here
U3. Sarah and Rony both got final grade adjustments: Sarah is now "A-" and Rony is now "A". Update both in a single operation.
1# your code here
Properties of dictionaries#
Now that you know the basic operations, let’s look at some properties of dictionaries. Instead of memorizing a list, let’s see what happens when we use our catalog in ways that bump into them.
1catalog = {
2 "INST126": "Intro to Programming",
3 "INST201": "Intro to Information Science",
4 "INST326": "Object-Oriented Programming"
5}
Dictionaries have length#
How many courses are in our catalog?
1len(catalog)
3
Similar to lists, dictionaries have length: len() counts the entries (the key-value pairs).
Dictionaries do not have positions#
What’s the first course in the catalog? With a list, we’d use [0]. Let’s try it:
1catalog[0]
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
Cell In[64], line 1
----> 1 catalog[0]
KeyError: 0
Look closely at the error: it’s a KeyError, not an IndexError! Python isn’t looking for position 0. It’s looking for a key that is the number 0, and there isn’t one.
Different from lists, dictionaries do not have positions. So you can’t grab things by position, and you can’t sort a dictionary in place either. You grab things by… key!
1# can't sort either
2catalog.sort()
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In[65], line 2
1 # can't sort either
----> 2 catalog.sort()
AttributeError: 'dict' object has no attribute 'sort'
1sorted(catalog) # this does *not* sort the dictionary; it returns a sorted list of the keys
['INST126', 'INST201', 'INST326']
Python does remember the order you put entries in. When we looped through the catalog above, the courses came back in the order we added them. But you still can’t ask for “the 3rd course”. If you need a sequence you can index into by position, use a list!
All keys in a dictionary are unique#
What happens if someone adds INST126 again, with a different title?
1catalog = {
2 "INST126": "Intro to Programming",
3 "INST201": "Intro to Information Science",
4 "INST126": "Programming for Information Science"
5}
6catalog
{'INST126': 'Programming for Information Science',
'INST201': 'Intro to Information Science'}
Only one INST126 survives: the last one. All keys in a dictionary have to be unique, so the second INST126 entry overwrote the first. (This is the same thing that happens when you .update() a key that’s already there.) This makes dictionaries handy for keeping track of unique items (in contrast to say, lists, where you can have duplicate entries).
Values in the dictionary do not have to be unique, though: different keys can point to the same value. For example, two different courses can have the same title:
1catalog = {
2 "INST126": "Intro to Programming",
3 "INST408Y": "Special Topics",
4 "INST408Z": "Special Topics"
5}
6catalog
{'INST126': 'Intro to Programming',
'INST408Y': 'Special Topics',
'INST408Z': 'Special Topics'}
But one key can’t point to two different values. There is a related data structure that has a similar property called sets if you’re interested.
Dictionaries are mutable#
Like lists, dictionaries are also mutable: you can modify them directly (in contrast to strings, where you never modify them directly, but only ever create a new modified version of the string).
One place this shows up is in functions. If you pass a dictionary into a function, and the function changes it, the change sticks around after the function is done.
1def add_course(catalog, code, title):
2 catalog.update({code: title}) # this changes the dictionary that was passed in
3 return catalog
4
5catalog = {"INST126": "Intro to Programming"}
6add_course(catalog, "INST201", "Intro to Information Science") # note: we don't save the result anywhere
7print(catalog) # the original catalog changed!
{'INST126': 'Intro to Programming', 'INST201': 'Intro to Information Science'}
We never did catalog = add_course(...), but catalog still has INST201 in it. This works the same way as with lists (remember “Lists are mutable” from the Lists chapter?). You’ll write functions like this in the PCE.
Anything goes for values#
So far, our values have all been strings. But basically anything goes for values. What if we want to keep track of each course’s prereqs? A course can have more than one prereq, so the value can be a list:
1prereqs = {
2 "INST126": [],
3 "INST326": ["INST126"],
4 "INST414": ["INST126", "INST201"]
5}
6prereqs.get("INST414")
['INST126', 'INST201']
You can even nest a dictionary inside another dictionary, by mapping a dictionary value to some key. We’ll do exactly that with our catalog in the next section! (Fun fact: values can even be functions. Not something we’ll need in this class, but it shows you how much anything goes.)
Keys must be hashable#
Keys are pickier. Say we want to keep track of which pairs of courses have a time conflict, so we try to use a pair of courses (a list) as the key:
1conflicts = {["INST126", "INST201"]: "both meet MWF at 10am"}
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[71], line 1
----> 1 conflicts = {["INST126", "INST201"]: "both meet MWF at 10am"}
TypeError: unhashable type: 'list'
Keys need to be hashable.
What does this mean?
From the Python glossary:
An object is hashable if it has a hash value which never changes during its lifetime (it needs a
__hash__()method), and can be compared to other objects (it needs an__eq__()method). Hashable objects which compare equal must have the same hash value.Hashability makes an object usable as a dictionary key and a set member, because these data structures use the hash value internally.
Most of Python’s immutable built-in objects are hashable; mutable containers (such as lists or dictionaries) are not; immutable containers (such as tuples and frozensets) are only hashable if their elements are hashable. Objects which are instances of user-defined classes are hashable by default. They all compare unequal (except with themselves), and their hash value is derived from their
id().
More info here: https://stackoverflow.com/questions/14535730/what-does-hashable-mean-in-python
I mention this because a common error when first working with dictionaries is to try to use an unhashable data structure as a key.
Understanding hashes is not something to worry about for now. We can focus on a basic rule of thumb: strings and numbers are ok as keys; lists and dictionaries are not.
Reverse lookup: YOU CAN’T! Not really…#
What if you want to go the other way? Say you know a title, and you want the course code. Dictionaries only look things up in one direction: from a key to its value. There’s no .get() for values. You have to loop through every entry and check:
1catalog = {
2 "INST126": "Intro to Programming",
3 "INST201": "Intro to Information Science",
4 "INST408Y": "Special Topics",
5 "INST408Z": "Special Topics"
6}
7
8query = "Special Topics" # the title we're looking for
9matches = [] # a list to collect every code with that title
10for code, title in catalog.items(): # check every entry, one by one
11 if title == query: # if this course has the title we want...
12 matches.append(code) # ...remember its code
13matches
['INST408Y', 'INST408Z']
We go through every course in the catalog. INST126 and INST201 don’t match, so we skip them. INST408Y and INST408Z both have the title “Special Topics”, so both of their codes get appended to matches.
This works, but it’s basically the slow list-style search from the start of the chapter. We’ve lost the quick lookup that made dictionaries useful in the first place!
Could we flip the dictionary around, so the titles are keys and the codes are values?
1def reverse_dictionary(d):
2 reversed_d = {}
3 for key, value in d.items():
4 reversed_d.update({value: key}) # flip it: the old value becomes the new key
5 return reversed_d
6
7reverse_dictionary(catalog)
{'Intro to Programming': 'INST126',
'Intro to Information Science': 'INST201',
'Special Topics': 'INST408Z'}
INST408Y disappeared! Remember: keys are unique. Both Special Topics courses tried to use “Special Topics” as a key, and INST408Z overwrote INST408Y.
Instead, we can map each title to a list of codes:
1titles_index = {}
2for code, title in catalog.items():
3 codes = titles_index.get(title, []) # the codes we've found for this title so far (or an empty list, if this is the first)
4 codes.append(code) # add this code to the list
5 titles_index.update({title: codes}) # and put the updated list back in the index
6titles_index
{'Intro to Programming': ['INST126'],
'Intro to Information Science': ['INST201'],
'Special Topics': ['INST408Y', 'INST408Z']}
This is a preview of the indexing pattern, which we’ll unpack properly at the end of the chapter! For now, notice that when we get to INST408Z, .get("Special Topics", []) gives back ["INST408Y"] (the list we already started), so INST408Z gets added to it instead of overwriting it.
The bigger lesson here: dictionaries make one specific kind of lookup REALLY easy, but lock you out of doing other things. So think about which questions you want to ask of your data before you design the structure of the dictionary.
Working with dictionaries: advanced (part 1): nested dictionaries#
Our catalog maps codes to titles. But a course has a lot more going on than a title: an instructor, credits, prereqs, a room, etc. So far, most of our dictionary values have been simple: a string, a number, a list. But one of the most powerful things about dictionaries is that values can be dictionaries too. This lets us model structured data (things with multiple attributes) in a very natural way.
Why nest?#
You could try to keep track of everything with separate variables:
1# one variable per piece of info
2INST126_title = "Intro to Programming"
3INST126_instructor = "Joel"
4INST126_credits = 3
5# ...and then the same again for every other course. This gets messy fast!
Or you could use a nested dictionary, where each course code maps to a dictionary of that course’s attributes:
1catalog = {
2 "INST126": {
3 "title": "Intro to Programming",
4 "instructor": "Joel",
5 "credits": 3,
6 "prereqs": []
7 },
8 "INST326": {
9 "title": "OO Programming",
10 "instructor": "Pat",
11 "credits": 3,
12 "prereqs": ["INST126"]
13 },
14 "INST414": {
15 "title": "Data Science",
16 "instructor": "Sarah",
17 "credits": 3,
18 "prereqs": ["INST126", "INST201"]
19 }
20}
This is much cleaner. Each course has a “record” of attributes, and we can look up any attribute for any course. (This is basically the catalog from the start of the chapter!)
Reading nested values: chain the lookups#
To get a value from a nested dictionary, you chain two lookups: first the outer key, then the inner key.
1# who teaches INST326?
2print(catalog["INST326"]["instructor"])
Pat
Notice that I’ve switched to the indexing style here. For nested dictionaries, catalog["INST326"]["instructor"] reads more naturally to me than catalog.get("INST326").get("instructor"). This is a good example of why it’s good to be comfortable with both styles!
Chaining: a familiar idea#
This idea of chaining should feel familiar from strings! Remember how we could chain string methods like .strip().lower().replace("#", "")? That worked because each method returned a string, so you could immediately call another method on it.
The same principle is at work here: each operation returns something, and you can immediately do another operation on that result.
" Hello ".strip()→ returns a string →.lower()works on itemail.split("@")[0]→.split()returns a list →[0]indexes into itcatalog["INST326"]["instructor"]→catalog["INST326"]returns a dictionary →["instructor"]looks up a key in it
It’s the same pattern every time: the result of one operation becomes the input to the next.
Breaking it into steps#
If chaining feels confusing, you can always break it into separate steps. It does the exact same thing:
1# step 1: get INST326's record (this gives us a dictionary)
2record = catalog["INST326"]
3print(type(record))
4print(record)
5
6# step 2: get the instructor from that dictionary
7print(record["instructor"])
<class 'dict'>
{'title': 'OO Programming', 'instructor': 'Pat', 'credits': 3, 'prereqs': ['INST126']}
Pat
The one-liner catalog["INST326"]["instructor"] just combines both steps. Think of it as reading left to right: “from catalog, get "INST326", then from that, get "instructor".”
Now we can answer all sorts of questions by chaining lookups:
1# what are the prereqs for INST414?
2print(catalog["INST414"]["prereqs"])
['INST126', 'INST201']
1# does INST126 have any prereqs?
2prereqs = catalog["INST126"]["prereqs"]
3if len(prereqs) == 0:
4 print("INST126 has no prerequisites")
5else:
6 print(f"INST126 requires: {prereqs}")
INST126 has no prerequisites
Safe chaining with .get()#
You can also chain .get() calls for safer access:
1# safe access with .get()
2print(catalog.get("INST326", {}).get("instructor", "TBD"))
3
4# if the outer key doesn't exist, .get() returns {},
5# and then .get("instructor") on {} returns "TBD"
6print(catalog.get("INST999", {}).get("instructor", "TBD"))
Pat
TBD
This works because .get("INST999", {}) returns an empty dictionary {} when "INST999" isn’t found, and then .get("instructor", "TBD") on that empty dictionary returns "TBD". Each step produces something the next step can work with.
Checking which key is missing#
Safe chaining has one downside. It can’t tell you which key was missing. Is the course not in the catalog at all, or is it there, but without that attribute? If you need to know (e.g., to give a helpful message), check each level with in, outer key first:
1def find_attribute(catalog, code, attribute):
2 # check the outer dictionary: is the course in the catalog?
3 if code not in catalog:
4 return f"Sorry, {code} is not in the catalog"
5 # if we get here, the course is there. now check the inner dictionary: does the course have this attribute?
6 if attribute not in catalog[code]:
7 return f"Sorry, {code} has no {attribute} listed"
8 # if we get here, both keys are there, so it's safe to chain the lookups
9 return catalog[code][attribute]
10
11print(find_attribute(catalog, "INST326", "instructor"))
12print(find_attribute(catalog, "INST999", "instructor"))
13print(find_attribute(catalog, "INST326", "room"))
Pat
Sorry, INST999 is not in the catalog
Sorry, INST326 has no room listed
This is the same in check from the basics, just done twice: once for the outer dictionary, and once for the inner one. The order matters! If you checked attribute not in catalog[code] first, catalog["INST999"] would crash with a KeyError before you got to give your nice message.
Updating nested values#
To update a value inside a nested dictionary, chain the lookups on the left side of the assignment:
1# Pat is no longer teaching INST326, Rony is
2catalog["INST326"]["instructor"] = "Rony"
3
4# INST326 added a new prereq
5catalog["INST326"]["prereqs"].append("INST201")
6
7print(catalog["INST326"])
{'title': 'OO Programming', 'instructor': 'Rony', 'credits': 3, 'prereqs': ['INST126', 'INST201']}
Notice that last line: catalog["INST326"]["prereqs"] gives us a list, and since lists are mutable, we can .append() to it directly. This is the power of nesting: the inner values follow all the rules of their own type.
Adding a new course (a new entry in the outer dictionary)#
To add a whole new record, assign a new dictionary to a new outer key. As with flat dictionaries, the keys and values can come from variables:
1# add a new course
2code = "INST314"
3title = "Statistics for Information Science"
4catalog[code] = {
5 "title": title,
6 "instructor": "Kacie",
7 "credits": 3,
8 "prereqs": []
9}
10print(catalog["INST314"])
{'title': 'Statistics for Information Science', 'instructor': 'Kacie', 'credits': 3, 'prereqs': []}
Adding a new field to a course (a new entry in an inner dictionary)#
You can also add new keys to an inner dictionary. It’s just a regular dictionary, after all:
1# add a room to INST126's record
2catalog["INST126"]["room"] = "HBK0302"
3print(catalog["INST126"])
{'title': 'Intro to Programming', 'instructor': 'Joel', 'credits': 3, 'prereqs': [], 'room': 'HBK0302'}
Common pattern: building nested dictionaries from data#
Often you’ll start with raw data (like a list of strings) and need to build up a nested dictionary. The pattern is the same as building a flat dictionary, but the value you create or update is itself a dictionary (or a list inside a dictionary).
1# raw catalog data: "code,title,instructor,credits"
2catalog_data = [
3 "INST126,Intro to Programming,Joel,3",
4 "INST326,OO Programming,Pat,3",
5 "INST414,Data Science,Sarah,3"
6]
7
8catalog = {}
9for entry in catalog_data:
10 # split "INST126,Intro to Programming,Joel,3" into its 4 pieces
11 code, title, instructor, credits = entry.split(",")
12 # the code is the outer key; the other pieces go in the course's record
13 catalog[code] = {
14 "title": title,
15 "instructor": instructor,
16 "credits": int(credits) # .split() gives us strings, so convert "3" to the number 3
17 }
18
19print(catalog)
{'INST126': {'title': 'Intro to Programming', 'instructor': 'Joel', 'credits': 3}, 'INST326': {'title': 'OO Programming', 'instructor': 'Pat', 'credits': 3}, 'INST414': {'title': 'Data Science', 'instructor': 'Sarah', 'credits': 3}}
1# now we can look up any course's info
2print(f"INST414 ({catalog['INST414']['title']}) is taught by {catalog['INST414']['instructor']}")
INST414 (Data Science) is taught by Sarah
Summary#
Working with nested dictionaries follows the same rules as flat dictionaries: you just chain the operations.
Operation |
Flat |
Nested |
|---|---|---|
Read |
|
|
Update |
|
|
Add outer entry |
|
|
Add inner field |
n/a |
|
Safe read |
|
|
Check |
|
|
Practice: Code Tracing with Nested Dictionaries#
Predict the output of each code snippet before running the cell!
Trace 1#
1users = {
2 "alice": {"role": "admin", "active": True},
3 "bob": {"role": "editor", "active": False}
4}
5print(users["alice"]["role"])
A)
aliceB)
adminC)
{'role': 'admin', 'active': True}D)
True
Answer:
B) admin
users["alice"] returns the inner dictionary {"role": "admin", "active": True}. Then ["role"] looks up the key "role" in that dictionary, which gives "admin".
Trace 2#
1menu = {
2 "burger": {"price": 12.99, "vegetarian": False},
3 "salad": {"price": 9.50, "vegetarian": True}
4}
5menu["burger"]["price"] = 13.99
6menu["salad"]["calories"] = 350
7print(menu["burger"]["price"])
8print(menu["salad"])
A)
12.99then{'price': 9.5, 'vegetarian': True}B)
13.99then{'price': 9.5, 'vegetarian': True, 'calories': 350}C)
13.99then{'price': 9.5, 'vegetarian': True}D)
12.99then{'price': 9.5, 'vegetarian': True, 'calories': 350}
Answer:
B) 13.99 then {'price': 9.5, 'vegetarian': True, 'calories': 350}
The first line updates burger’s price from 12.99 to 13.99. The second line adds a new key "calories" to salad’s inner dictionary — you can add fields to an inner dict just like any other dictionary.
Trace 3#
1catalog = {
2 "INST126": {"instructor": "Joel", "enrolled": 38},
3 "INST326": {"instructor": "Pat", "enrolled": 22}
4}
5catalog["INST326"]["enrolled"] += 3
6result = catalog.get("INST201", {}).get("instructor", "TBD")
7print(catalog["INST326"]["enrolled"])
8print(result)
A)
22thenTBDB)
25thenTBDC)
25then KeyErrorD)
3then{}
Answer:
B) 25 then TBD
+= 3 adds 3 to the current enrolled count (22 → 25). For the .get() chain: "INST201" isn’t in the catalog, so the first .get() returns {} (the default). Then .get("instructor", "TBD") on that empty dictionary returns "TBD". No crash — that’s the advantage of safe chaining with .get().
Trace 4#
1shows = {
2 "Breaking Bad": {"genre": "drama", "seasons": 5},
3 "The Office": {"genre": "comedy", "seasons": 9}
4}
5shows["Friends"] = {"genre": "comedy", "seasons": 10}
6print(len(shows))
7print(shows["Friends"]["seasons"])
A)
2then KeyErrorB)
3then10C)
3then{"genre": "comedy", "seasons": 10}D)
2then10
Answer:
B) 3 then 10
Assigning to shows["Friends"] adds a new outer key with a full dictionary as its value. shows now has 3 entries. shows["Friends"]["seasons"] chains into the new entry and returns 10.
Trace 5#
1profiles = {
2 "terp1": {"name": "Joel", "followers": 100},
3 "terp2": {"name": "Sarah", "followers": 250}
4}
5profiles["terp1"]["followers"] += 50
6profiles["terp2"]["name"] = profiles["terp2"]["name"].upper()
7print(profiles["terp1"]["followers"])
8print(profiles["terp2"]["name"])
A)
100thenSarahB)
150thenSARAHC)
50thenSARAHD)
150thenSarah
Answer:
B) 150 then SARAH
+= 50 adds 50 to terp1’s follower count (100 → 150). For terp2’s name: profiles["terp2"]["name"] returns "Sarah", then .upper() returns "SARAH", and that result is assigned back. Notice the chaining: we read a nested value, call a string method on it, and assign the result back to the same nested location.
Trace 6#
1data = {}
2entries = ["Joel:A:INST126", "Sarah:B:INST201", "Joel:A+:INST326"]
3for entry in entries:
4 name, grade, course = entry.split(":")
5 data[name] = {"grade": grade, "course": course}
6print(data["Joel"]["grade"])
7print(len(data))
A)
Athen3B)
A+then2C)
Athen2D)
A+then3
Answer:
B) A+ then 2
Joel appears twice. The second entry ("Joel:A+:INST326") overwrites the first — keys are unique, so data["Joel"] ends up as {"grade": "A+", "course": "INST326"}. There are only 2 unique names (Joel and Sarah), so len(data) is 2.
Practice: Dictionary Scenarios (nested)#
Same as before: for each scenario, complete the retrieval and update operations. This time, the dictionaries are nested, and the starting dictionary is written for you: just run its cell first.
Scenario 4: Course directory (nested)#
You’re building a course directory where each course code maps to a dictionary of course details.
Setup#
Here’s the starting courses dictionary. Run this cell to create it:
1courses = {
2 "INST126": {"title": "Intro to Programming", "instructor": "Joel", "capacity": 40, "enrolled": 38},
3 "INST201": {"title": "Intro to Info Science", "instructor": "Sarah", "capacity": 35, "enrolled": 35},
4 "INST326": {"title": "OO Programming", "instructor": "Pat", "capacity": 30, "enrolled": 22}
5}
Retrieve#
R1. Print the instructor for INST126.
1# your code here
R2. Print how many open seats INST126 has (capacity minus enrolled), formatted as: "INST126: {n} seats available".
1# your code here
R3. A student wants to know the title and instructor for INST326. Print: "INST326: OO Programming (taught by Pat)".
1# your code here
Update#
U1. 3 more students enrolled in INST326. Update the enrolled count.
1# your code here
U2. INST201 got a new instructor: “Rony”. Update it.
1# your code here
U3. Add a new course: "INST314" with title "Statistics", instructor "Kacie", capacity 25, and enrolled 0.
1# your code here
Scenario 5: Streaming catalog (nested)#
You’re modeling a simple streaming catalog where each show title maps to a dictionary of details.
Setup#
Here’s the starting catalog dictionary. Run this cell to create it:
1catalog = {
2 "Stranger Things": {"genre": "sci-fi", "seasons": 4, "rating": 8.7},
3 "The Office": {"genre": "comedy", "seasons": 9, "rating": 8.9},
4 "Breaking Bad": {"genre": "drama", "seasons": 5, "rating": 9.5},
5 "Ted Lasso": {"genre": "comedy", "seasons": 3, "rating": 8.8}
6}
Retrieve#
R1. Print the rating of Breaking Bad.
1# your code here
R2. Print how many seasons The Office has, formatted as: "The Office: 9 seasons".
1# your code here
R3. Check if “Wednesday” is in the catalog. Print "Wednesday is available" or "Wednesday is not in the catalog".
1# your code here
Update#
U1. Stranger Things released a new season. Update its season count to 5.
1# your code here
U2. After the new season, the rating for Stranger Things was updated to 8.9. Update it.
1# your code here
U3. Add a new show: "Wednesday" with genre "comedy", seasons 1, and rating 8.1.
1# your code here
Scenario 6: Website config (nested)#
You’re working with a website configuration dictionary that stores settings for different sections of the site.
Setup#
Here’s the starting config dictionary. Run this cell to create it:
1config = {
2 "homepage": {"title": "Welcome", "show_banner": True, "max_posts": 10},
3 "blog": {"title": "Our Blog", "show_banner": False, "max_posts": 25},
4 "about": {"title": "About Us", "show_banner": True, "max_posts": 0}
5}
Retrieve#
R1. Print the title of the blog page.
1# your code here
R2. Check whether the blog page has the banner enabled. Print "Blog banner: on" or "Blog banner: off" accordingly.
1# your code here
R3. Print the homepage title and max posts, formatted as: "Homepage: 'Welcome' (max 10 posts)".
1# your code here
Update#
U1. Enable the banner on the blog page.
1# your code here
U2. The homepage should now show a max of 15 posts instead of 10. Update it.
1# your code here
U3. Add a new page: "contact" with title "Contact Us", show_banner set to False, and max_posts set to 0.
1# your code here
Working with dictionaries: advanced (part 2): building dictionaries from data (indexing)#
Remember the reverse lookup problem from the properties section? Dictionaries make it really easy to ask one kind of question, so if we want to ask a different kind of question, we can build a new dictionary that’s designed for it. This is what an index is (just like the index in the back of a book!).
Which courses does each instructor teach?#
Our catalog maps courses to their details, so “who teaches INST326?” is a quick lookup. But “which courses does Joel teach?” isn’t: we’d have to loop through every course. So let’s build an index that maps each instructor to a list of their courses:
1catalog = {
2 "INST126": {"title": "Intro to Programming", "instructor": "Joel"},
3 "INST326": {"title": "OO Programming", "instructor": "Pat"},
4 "INST414": {"title": "Data Science", "instructor": "Sarah"},
5 "INST314": {"title": "Statistics for Information Science", "instructor": "Joel"}
6}
7
8# make a dictionary to hold the index
9by_instructor = {}
10
11# go through every course
12for code, info in catalog.items():
13 # the instructor is the key we want to index by
14 instructor = info["instructor"]
15 # get the current list of courses for this instructor (or an empty list, if we haven't seen them yet)
16 courses = by_instructor.get(instructor, [])
17 # add this course to the list
18 courses.append(code)
19 # and update the index
20 by_instructor.update({instructor: courses})
21
22by_instructor
{'Joel': ['INST126', 'INST314'], 'Pat': ['INST326'], 'Sarah': ['INST414']}
Now “which courses does Joel teach?” is a quick lookup again:
1by_instructor.get("Joel")
['INST126', 'INST314']
Back to the book index#
Here’s the book index from the start of the chapter. This time, instead of typing out the index by hand, we’ll write a program that builds it: it takes a list of book chapter strings and a list of key concepts, and produces an index that maps key concepts to chapters.
1# how to know which chapters talk about strings? or debugging?
2book = [
3 "Chapter 1: talks about strings and how they have the property of immutability also some basic debugging",
4 "Chapter 2: continues talking about advanced methods for strings and also introduces the concept of functions",
5 "Chapter 3: discusses iteration and lists and also debugging",
6]
1# define what we want to index as keys
2concepts = ['strings', 'debugging', "lists", "iteration"]
3
4# make a dictionary to hold the index
5index = {}
6
7# go through every chapter
8for entry in book:
9
10 # split into chapter and descr based on the colon
11 chapter, descr = entry.split(":")
12
13 # index the concepts
14
15 # for every concept we care about
16 for keyconcept in concepts:
17 # check if it's in this chapter descr
18 if keyconcept in descr:
19 # if so, get the current list of chapters associated with this keyconcept
20 chs = index.get(keyconcept, [])
21 # then update the list of chapters
22 # if we haven't seen the chapter
23 if chapter not in chs:
24 chs.append(chapter)
25 # and update the index to map the keyconcept to the updated list of assoc. chapters
26 index.update({keyconcept: chs})
27index
{'strings': ['Chapter 1', 'Chapter 2'],
'debugging': ['Chapter 1', 'Chapter 3'],
'lists': ['Chapter 3'],
'iteration': ['Chapter 3']}
What dictionary concepts do you recognize?
The indexing pattern#
Here’s the generic structure of an indexing pattern:
1# create an empty dictionary to hold the index
2
3# for every item in a list of things you want to index
4
5 # (optional: parse out the keys and values you want to index from the item)
6
7 # get the current value associated with the key in the index
8
9 # update the value
10
11 # update the index with the key and its updated value
Connection to patterns you already know#
This pattern might look new, but the core idea is something you’ve already practiced! In earlier chapters, we used two loop patterns over and over:
Counting: initialize a counter to
0, loop through items, increment the counter when a condition is metAccumulating (into a list): initialize an empty list
[], loop through items,.append()items that meet some criteria
Dictionary indexing is just these same patterns — but instead of one counter or one list, you have a counter or list per key. The dictionary is what lets you keep track of multiple accumulators at once, one for each unique key.
Here’s the side-by-side:
Simple (from Iteration) |
Dictionary version (Indexing) |
|
|---|---|---|
Counting |
|
|
Accumulating |
|
|
The key difference is .get(key, default) — it handles the “first time we see this key” case by providing a starting value (0 for counting, [] for accumulating).
Let’s see both variations in action.
Variation 1: the counter pattern#
Let’s look at a super simple example: making a word count index.
We’ll take in a list of words, and produce an index that maps words as keys to counts of occurrences as values.
1# the thing we want to index
2word_list = ['she', 'sells', 'sea', 'shells', 'by', 'the', 'sea', 'shore', 'in', 'the', 'sea', 'and', 'the', 'shells', 'and', 'the', 'sea', 'sea', 'sea']
3
4# create an empty dictionary to hold the index
5word_counts = {}
6
7# for every item in a list of things you want to index
8for word in word_list:
9
10 # (optional: parse out the keys and values you want to index from the item)
11 # we don't need this step
12
13 # get the current value associated with the key in the index
14 # here, we use .get(), and have a default count of 0 if the key isn't yet in the index
15 count = word_counts.get(word, 0)
16
17 # update the value
18 count += 1
19
20 # update the index with the key and its updated value
21 word_counts.update({word: count})
22
23word_counts
{'she': 1,
'sells': 1,
'sea': 6,
'shells': 2,
'by': 1,
'the': 4,
'shore': 1,
'in': 1,
'and': 2}
Here’s the exact same update, squished into one line. This is the version I’d like you to get comfortable with (it’s also the one the PCE asks for!):
1word_counts = {}
2for word in word_list:
3 word_counts[word] = word_counts.get(word, 0) + 1 # get the old count, add 1, store it back
4word_counts
{'she': 1,
'sells': 1,
'sea': 6,
'shells': 2,
'by': 1,
'the': 4,
'shore': 1,
'in': 1,
'and': 2}
How to read that line: Python does the right side of the = first. word_counts.get(word, 0) gets the old count (or 0, if we haven’t seen the word yet), and + 1 adds one to it. Then the result gets stored under that word. So the first time we see “sea”, the right side is 0 + 1, and word_counts["sea"] becomes 1. The second time, the right side is 1 + 1, and it becomes 2.
And here’s what it looks like without .get(), using a conditional instead:
1word_counts = {}
2for word in word_list:
3 if word in word_counts: # we've seen this word before
4 word_counts[word] = word_counts[word] + 1 # so add 1 to its count
5 else: # first time we're seeing this word
6 word_counts[word] = 1 # so its count starts at 1
7word_counts
{'she': 1,
'sells': 1,
'sea': 6,
'shells': 2,
'by': 1,
'the': 4,
'shore': 1,
'in': 1,
'and': 2}
All three versions work! But .get() with a default handles the “first time we see this key” case for you, so there’s less to keep track of.
In the PCE and Project 3, this is called the counter pattern: you’ll use it for things like counting wins per team, or checkouts per book.
Practice: index grade counts#
Practice! Test your understanding by adapting the above code to count how many times each grade was earned in a course.
1grades = ["A", "B", "A", "C", "B+", "A", "B", "A-", "B", "A"]
2grades_counts = {}
Answer:
1grades = ["A", "B", "A", "C", "B+", "A", "B", "A-", "B", "A"]
2grades_counts = {}
3for grade in grades:
4 count = grades_counts.get(grade, 0)
5 count += 1
6 grades_counts.update({grade: count})
7grades_counts # {'A': 4, 'B': 3, 'C': 1, 'B+': 1, 'A-': 1}
1# your code here
Variation 2: the list-accumulator pattern#
The counting version uses d.get(key, 0) to start each key’s count at 0. But what if instead of counting, you want to collect items — like building a list of all chapters where a concept appears, or all emails from a particular sender?
This is the accumulating variation (in the PCE and Project 3, it’s called the list-accumulator pattern: e.g., grouping donations by team, or posts by user). Instead of 0 as the default, you use [] (an empty list), and instead of += 1, you .append() the item.
Actually, we’ve already seen a couple of these! The instructor index and the book index at the start of this section are both accumulating indexes. In the book index, the key is a concept, and the value is a list of chapters. index.get(keyconcept, []) starts each list off empty, and .append(chapter) adds to it.
Practice: which words are n characters long?#
Let’s try the accumulating variation. We’ll index word lengths: we want an index that can tell us “what words in the list were 2 characters long, or 5 characters long?” The key is the word length, and the value is a list of words with that length.
1# the thing we want to index
2word_list = ['she', 'sells', 'sea', 'shells', 'by', 'the', 'sea', 'shore', 'in', 'the', 'sea', 'and', 'the', 'shells', 'and', 'the', 'sea', 'sea', 'sea']
3
4# your code here
Answer:
1length_index = {}
2for word in word_list:
3 length = len(word)
4 words = length_index.get(length, [])
5 words.append(word)
6 length_index.update({length: words})
7length_index
8# {3: ['she', 'sea', 'the', 'sea', ...], 5: ['sells', 'shore'], 6: ['shells', 'shells'], 2: ['by', 'in']}
Notice the duplicates: “sea” shows up 6 times in the 3s! If you only want each word once, check if word not in words: before you append (just like the book index does with chapters).
Practice: counts of email addresses from email records (counting)#
Let’s practice the counting variation again. Index how many times we got emails from each email address!
1email_records = ['From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008',
2 'From louis@media.berkeley.edu Fri Jan 4 18:10:48 2008',
3 'From zqian@umich.edu Fri Jan 4 16:10:39 2008',
4 'From rjlowe@iupui.edu Fri Jan 4 15:46:24 2008',
5 'From zqian@umich.edu Fri Jan 4 15:03:18 2008',
6 'From rjlowe@iupui.edu Fri Jan 4 14:50:18 2008',
7 'From cwen@iupui.edu Fri Jan 4 11:37:30 2008',
8 'From cwen@iupui.edu Fri Jan 4 11:35:08 2008',
9 'From gsilver@umich.edu Fri Jan 4 11:12:37 2008',
10 'From gsilver@umich.edu Fri Jan 4 11:11:52 2008',
11 'From zqian@umich.edu Fri Jan 4 11:11:03 2008',
12 'From gsilver@umich.edu Fri Jan 4 11:10:22 2008',
13 'From wagnermr@iupui.edu Fri Jan 4 10:38:42 2008',
14 'From zqian@umich.edu Fri Jan 4 10:17:43 2008',
15 'From antranig@caret.cam.ac.uk Fri Jan 4 10:04:14 2008',
16 'From gopal.ramasammycook@gmail.com Fri Jan 4 09:05:31 2008',
17 'From david.horwitz@uct.ac.za Fri Jan 4 07:02:32 2008',
18 'From david.horwitz@uct.ac.za Fri Jan 4 06:08:27 2008',
19 'From david.horwitz@uct.ac.za Fri Jan 4 04:49:08 2008',
20 'From david.horwitz@uct.ac.za Fri Jan 4 04:33:44 2008',
21 'From stephen.marquard@uct.ac.za Fri Jan 4 04:07:34 2008',
22 'From louis@media.berkeley.edu Thu Jan 3 19:51:21 2008',
23 'From louis@media.berkeley.edu Thu Jan 3 17:18:23 2008',
24 'From ray@media.berkeley.edu Thu Jan 3 17:07:00 2008',
25 'From cwen@iupui.edu Thu Jan 3 16:34:40 2008',
26 'From cwen@iupui.edu Thu Jan 3 16:29:07 2008',
27 'From cwen@iupui.edu Thu Jan 3 16:23:48 2008']
28
29# your code here
Answer:
1email_counts = {}
2for record in email_records:
3 email = record.split()[1] # "From cwen@iupui.edu Fri ..." -> the 2nd word is the address
4 count = email_counts.get(email, 0)
5 count += 1
6 email_counts.update({email: count})
7email_counts # {'stephen.marquard@uct.ac.za': 2, 'louis@media.berkeley.edu': 3, ... 'cwen@iupui.edu': 5, ...}
Practice: map email addresses to email records (accumulating)#
Now modify the previous program to use the accumulating variation. Instead of counting, collect the full email records (as a list of strings) for each email address. We want to ask questions like “can I see the emails I got from cwen@iupui.edu?” Call your dictionary email_occurrences.
1email_records = ['From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008',
2 'From louis@media.berkeley.edu Fri Jan 4 18:10:48 2008',
3 'From zqian@umich.edu Fri Jan 4 16:10:39 2008',
4 'From rjlowe@iupui.edu Fri Jan 4 15:46:24 2008',
5 'From zqian@umich.edu Fri Jan 4 15:03:18 2008',
6 'From rjlowe@iupui.edu Fri Jan 4 14:50:18 2008',
7 'From cwen@iupui.edu Fri Jan 4 11:37:30 2008',
8 'From cwen@iupui.edu Fri Jan 4 11:35:08 2008',
9 'From gsilver@umich.edu Fri Jan 4 11:12:37 2008',
10 'From gsilver@umich.edu Fri Jan 4 11:11:52 2008',
11 'From zqian@umich.edu Fri Jan 4 11:11:03 2008',
12 'From gsilver@umich.edu Fri Jan 4 11:10:22 2008',
13 'From wagnermr@iupui.edu Fri Jan 4 10:38:42 2008',
14 'From zqian@umich.edu Fri Jan 4 10:17:43 2008',
15 'From antranig@caret.cam.ac.uk Fri Jan 4 10:04:14 2008',
16 'From gopal.ramasammycook@gmail.com Fri Jan 4 09:05:31 2008',
17 'From david.horwitz@uct.ac.za Fri Jan 4 07:02:32 2008',
18 'From david.horwitz@uct.ac.za Fri Jan 4 06:08:27 2008',
19 'From david.horwitz@uct.ac.za Fri Jan 4 04:49:08 2008',
20 'From david.horwitz@uct.ac.za Fri Jan 4 04:33:44 2008',
21 'From stephen.marquard@uct.ac.za Fri Jan 4 04:07:34 2008',
22 'From louis@media.berkeley.edu Thu Jan 3 19:51:21 2008',
23 'From louis@media.berkeley.edu Thu Jan 3 17:18:23 2008',
24 'From ray@media.berkeley.edu Thu Jan 3 17:07:00 2008',
25 'From cwen@iupui.edu Thu Jan 3 16:34:40 2008',
26 'From cwen@iupui.edu Thu Jan 3 16:29:07 2008',
27 'From cwen@iupui.edu Thu Jan 3 16:23:48 2008']
28
29# your code here
30
31# when you're done, try looking up an address:
32# email_occurrences.get("david.horwitz@uct.ac.za")
Answer:
1email_occurrences = {}
2for record in email_records:
3 email = record.split()[1]
4 records = email_occurrences.get(email, [])
5 records.append(record)
6 email_occurrences.update({email: records})
7email_occurrences.get("david.horwitz@uct.ac.za") # a list of 4 records
Compare this to the counting version: the only changes are the default ([] instead of 0), and .append(record) instead of += 1.
Investigate: integrate the book chapter indexing program into our generic structure#
What’s the same? What needs to be modified?
Answer:
What’s the same: an empty dictionary to hold the index, a loop through the items (chapters), .get(keyconcept, []) to get the current value, then updating the value and the index.
What’s modified:
The parse step splits each entry into a chapter and a description.
One chapter can produce several keys (concepts), so there’s a second loop inside the first one.
There’s a conditional: we only index a concept if it’s in the description.
There’s an extra check so we don’t add the same chapter twice.
Practice: flag important emails#
Let’s say you have a list of ‘starred contacts’, and you want a separate index where you can ask the question “give me all the emails I got from this starred contact”. You can imagine this being sort of a rudimentary back-end of your “important” tab in Gmail.
How might we modify our email indexing program to do this?
1email_records = ['From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008',
2 'From louis@media.berkeley.edu Fri Jan 4 18:10:48 2008',
3 'From zqian@umich.edu Fri Jan 4 16:10:39 2008',
4 'From rjlowe@iupui.edu Fri Jan 4 15:46:24 2008',
5 'From zqian@umich.edu Fri Jan 4 15:03:18 2008',
6 'From rjlowe@iupui.edu Fri Jan 4 14:50:18 2008',
7 'From cwen@iupui.edu Fri Jan 4 11:37:30 2008',
8 'From cwen@iupui.edu Fri Jan 4 11:35:08 2008',
9 'From gsilver@umich.edu Fri Jan 4 11:12:37 2008',
10 'From gsilver@umich.edu Fri Jan 4 11:11:52 2008',
11 'From zqian@umich.edu Fri Jan 4 11:11:03 2008',
12 'From gsilver@umich.edu Fri Jan 4 11:10:22 2008',
13 'From wagnermr@iupui.edu Fri Jan 4 10:38:42 2008',
14 'From zqian@umich.edu Fri Jan 4 10:17:43 2008',
15 'From antranig@caret.cam.ac.uk Fri Jan 4 10:04:14 2008',
16 'From gopal.ramasammycook@gmail.com Fri Jan 4 09:05:31 2008',
17 'From david.horwitz@uct.ac.za Fri Jan 4 07:02:32 2008',
18 'From david.horwitz@uct.ac.za Fri Jan 4 06:08:27 2008',
19 'From david.horwitz@uct.ac.za Fri Jan 4 04:49:08 2008',
20 'From david.horwitz@uct.ac.za Fri Jan 4 04:33:44 2008',
21 'From stephen.marquard@uct.ac.za Fri Jan 4 04:07:34 2008',
22 'From louis@media.berkeley.edu Thu Jan 3 19:51:21 2008',
23 'From louis@media.berkeley.edu Thu Jan 3 17:18:23 2008',
24 'From ray@media.berkeley.edu Thu Jan 3 17:07:00 2008',
25 'From cwen@iupui.edu Thu Jan 3 16:34:40 2008',
26 'From cwen@iupui.edu Thu Jan 3 16:29:07 2008',
27 'From cwen@iupui.edu Thu Jan 3 16:23:48 2008']
28
29starred = ["cwen@iupui.edu", "david.horwitz@uct.ac.za"]
30# your code here
Answer:
1starred_emails = {}
2for record in email_records:
3 email = record.split()[1]
4 if email in starred:
5 records = starred_emails.get(email, [])
6 records.append(record)
7 starred_emails.update({email: records})
8starred_emails.get("cwen@iupui.edu") # 5 records
This is the accumulating program from before, plus one conditional: the filtering pattern!
Practice: Code Tracing with Dictionary Indexing#
Predict the output of each code snippet before running the cell!
Trace 1 (counting)#
1letters = ["a", "b", "a", "c", "b", "a"]
2counts = {}
3for letter in letters:
4 counts[letter] = counts.get(letter, 0) + 1
5print(counts)
6print(counts["a"])
A)
{'a': 1, 'b': 1, 'c': 1}then1B)
{'a': 3, 'b': 2, 'c': 1}then3C)
{'a': 3, 'b': 2, 'a': 3, 'c': 1, 'b': 2, 'a': 3}then3D)
{'a': 2, 'b': 1, 'c': 1}then2
Answer:
B) {'a': 3, 'b': 2, 'c': 1} then 3
Each time we see a letter, .get(letter, 0) returns the current count (or 0 if it’s new), and we add 1. “a” appears 3 times, “b” twice, “c” once. Keys are unique — there’s only one entry per letter.
Trace 2 (accumulating)#
1words = ["cat", "car", "dog", "cup"]
2groups = {}
3for word in words:
4 first = word[0]
5 items = groups.get(first, [])
6 items.append(word)
7 groups[first] = items
8print(groups)
A)
{'c': ['cup'], 'd': ['dog']}B)
{'c': ['cat', 'car', 'cup'], 'd': ['dog']}C)
{'cat': 'c', 'car': 'c', 'dog': 'd', 'cup': 'c'}D)
{'c': 3, 'd': 1}
Answer:
B) {'c': ['cat', 'car', 'cup'], 'd': ['dog']}
This is the accumulating pattern. The key is the first letter, and the value is a list of words starting with that letter. .get(first, []) returns the existing list or an empty one for new keys. Each word is appended to the appropriate list.
Trace 3 (counting with parsing)#
1sales = ["apples:3", "bananas:2", "apples:1", "bananas:5"]
2totals = {}
3for sale in sales:
4 item, qty = sale.split(":")
5 totals[item] = totals.get(item, 0) + int(qty)
6print(totals)
A)
{'apples': 1, 'bananas': 5}B)
{'apples': 4, 'bananas': 7}C)
{'apples': 3, 'bananas': 2}D)
{'apples:3': 1, 'bananas:2': 1, 'apples:1': 1, 'bananas:5': 1}
Answer:
B) {'apples': 4, 'bananas': 7}
Each entry is parsed with .split(":"). The quantity is converted to int and added to the running total for that item. Apples: 3 + 1 = 4. Bananas: 2 + 5 = 7. This is the counting pattern but accumulating a sum rather than just counting occurrences.
Trace 4 (trap — overwrite, not accumulate!)#
1scores = [("Joel", 85), ("Sarah", 92), ("Joel", 90), ("Sarah", 88)]
2record = {}
3for name, score in scores:
4 record[name] = score
5print(record)
A)
{'Joel': [85, 90], 'Sarah': [92, 88]}B)
{'Joel': 90, 'Sarah': 88}C)
{'Joel': 85, 'Sarah': 92}D)
{'Joel': 175, 'Sarah': 180}
Answer:
B) {'Joel': 90, 'Sarah': 88}
This is a trap! The code just assigns record[name] = score — it overwrites the previous value each time. Joel’s second score (90) replaces 85. To keep all scores, you’d need the accumulating pattern: record[name] = record.get(name, []) then record[name].append(score).
Trace 5 (counting with conditional)#
1grades = ["A", "B", "A", "C", "A", "B", "F", "B", "A"]
2passing = {}
3for grade in grades:
4 if grade != "F":
5 passing[grade] = passing.get(grade, 0) + 1
6print(passing)
7print(len(passing))
A)
{'A': 4, 'B': 3, 'C': 1, 'F': 1}then4B)
{'A': 4, 'B': 3, 'C': 1}then3C)
{'A': 4, 'B': 3, 'C': 1, 'F': 0}then4D)
{'A': 3, 'B': 2, 'C': 1}then3
Answer:
B) {'A': 4, 'B': 3, 'C': 1} then 3
The if grade != "F" filter means F is never added to the dictionary at all — not even with a count of 0. Only passing grades are counted. There are 3 unique passing grades, so len(passing) is 3.
Trace 6 (accumulating with parsing)#
1data = ["INST126:Joel", "INST201:Sarah", "INST126:Rony"]
2index = {}
3for entry in data:
4 course, student = entry.split(":")
5 students = index.get(course, [])
6 students.append(student)
7 index[course] = students
8print(index["INST126"])
9print(len(index))
A)
['Joel']then3B)
['Joel', 'Rony']then2C)
['Rony']then2D)
['Joel', 'Rony']then3
Answer:
B) ['Joel', 'Rony'] then 2
INST126 appears twice. The first time, .get("INST126", []) returns [], and “Joel” is appended. The second time, it returns ['Joel'], and “Rony” is appended. The list grows — it doesn’t overwrite. There are 2 unique courses, so len(index) is 2.
Practice: Dictionary Indexing Problems#
P1: Count character types (counting)#
Given a string, count how many letters, digits, and spaces it contains. Store the results in a dictionary with keys "letters", "digits", and "spaces".
1text = "Hello World 123"
2char_counts = {}
3
4# your code here
Answer:
1text = "Hello World 123"
2char_counts = {}
3for char in text:
4 if char.isalpha():
5 char_counts["letters"] = char_counts.get("letters", 0) + 1
6 elif char.isnumeric():
7 char_counts["digits"] = char_counts.get("digits", 0) + 1
8 elif char == " ":
9 char_counts["spaces"] = char_counts.get("spaces", 0) + 1
10char_counts # {'letters': 10, 'digits': 3, 'spaces': 2}
P2: Group names by first letter (accumulating)#
Given a list of names, build a dictionary that maps each first letter to a list of names starting with that letter.
1names = ["Joel", "Sarah", "John", "Kacie", "Sam", "Jill", "Kelly"]
2groups = {}
3
4# your code here
Answer:
1names = ["Joel", "Sarah", "John", "Kacie", "Sam", "Jill", "Kelly"]
2groups = {}
3for name in names:
4 first = name[0]
5 groups[first] = groups.get(first, [])
6 groups[first].append(name)
7groups # {'J': ['Joel', 'John', 'Jill'], 'S': ['Sarah', 'Sam'], 'K': ['Kacie', 'Kelly']}
P3: Word frequency from a sentence (counting)#
Given a sentence, count how many times each word appears. Normalize to lowercase first so “The” and “the” are counted together.
1sentence = "the cat sat on the mat and the cat saw the dog"
2word_freq = {}
3
4# your code here
Answer:
1sentence = "the cat sat on the mat and the cat saw the dog"
2word_freq = {}
3for word in sentence.lower().split():
4 word_freq[word] = word_freq.get(word, 0) + 1
5word_freq # {'the': 4, 'cat': 2, 'sat': 1, 'on': 1, 'mat': 1, 'and': 1, 'saw': 1, 'dog': 1}
P4: Categorize scores (accumulating)#
Given a list of scores, build a dictionary that groups them into "high" (90+), "medium" (70-89), and "low" (below 70).
1scores = [95, 67, 82, 91, 55, 73, 88, 100, 42, 78]
2categories = {}
3
4# your code here
Answer:
1scores = [95, 67, 82, 91, 55, 73, 88, 100, 42, 78]
2categories = {}
3for score in scores:
4 if score >= 90:
5 label = "high"
6 elif score >= 70:
7 label = "medium"
8 else:
9 label = "low"
10 categories[label] = categories.get(label, [])
11 categories[label].append(score)
12categories # {'high': [95, 91, 100], 'medium': [82, 73, 88, 78], 'low': [67, 55, 42]}
P5: Count email domains (counting)#
Given a list of email addresses, count how many emails come from each domain (the part after @).
1emails = ["joel@umd.edu", "sarah@gmail.com", "rony@umd.edu", "pat@gmail.com", "kacie@umd.edu", "miles@yahoo.com"]
2domain_counts = {}
3
4# your code here
Answer:
1emails = ["joel@umd.edu", "sarah@gmail.com", "rony@umd.edu", "pat@gmail.com", "kacie@umd.edu", "miles@yahoo.com"]
2domain_counts = {}
3for email in emails:
4 domain = email.split("@")[1]
5 domain_counts[domain] = domain_counts.get(domain, 0) + 1
6domain_counts # {'umd.edu': 3, 'gmail.com': 2, 'yahoo.com': 1}
P6: Index course enrollments (accumulating)#
Given a list of enrollment records in the format "StudentName:CourseCode", build a dictionary that maps each course to a list of enrolled students.
1enrollments = [
2 "Joel:INST126", "Sarah:INST201", "Rony:INST126",
3 "Kacie:INST201", "Pat:INST126", "Miles:INST326",
4 "Sarah:INST126", "Joel:INST201"
5]
6course_roster = {}
7
8# your code here
Answer:
1enrollments = [
2 "Joel:INST126", "Sarah:INST201", "Rony:INST126",
3 "Kacie:INST201", "Pat:INST126", "Miles:INST326",
4 "Sarah:INST126", "Joel:INST201"
5]
6course_roster = {}
7for entry in enrollments:
8 student, course = entry.split(":")
9 course_roster[course] = course_roster.get(course, [])
10 course_roster[course].append(student)
11course_roster
12# {'INST126': ['Joel', 'Rony', 'Pat', 'Sarah'],
13# 'INST201': ['Sarah', 'Kacie', 'Joel'],
14# 'INST326': ['Miles']}