In Session 2, we start working with CSV files using dictionary-style rows. This is quite different from arrays, because we can use column names as keys to access data (not indexes anymore).
First, you will practice core CSV dictionary logic using:
csv.DictReader- key-based access (for example
row["title"]) - counters
forloopsbreakfor first-match search
Before starting:
- Open the
session2folder in Visual Studio Code. - Create and activate your virtual environment:
python3 -m venv .venv
source .venv/bin/activateWindows PowerShell:
python -m venv .venv
.venv\Scripts\Activate.ps1- Install requirements:
pip install -r requirements.txt- Create your exercise file inside
session2/solutions, for example:
session2/solutions/exercise-02-01.pyThe csv.DictReader(file) reads each CSV row as a dict (dictionary). Keys come from the header row (column names). Values are still strings, so numeric conversion is manual when needed.
Let's start with the basics of dictionaries.
A Python dictionary lets you store data as key → value pairs (like word → meaning). Instead of using numbers like lists, you use names (keys) to find values, which is easier to read and understand.
person = {
"name": "Stelios",
"age": 20, # I wish
"city": "London"
}Access values
print(person["name"]) # SteliosAdd or change values
person["job"] = "Developer" # add new
person["city"] = "Athens" # updateRemove values
del person["city"]Loop through dictionary using items()
for key, value in person.items():
print(key, value)To run this tutorial, first download movies.csv from the Hugging Face repo: Birkbeck/movies
hf download Birkbeck/movies movies.csv --repo-type dataset --local-dir .Expected result: movies.csv appears in your current folder.
Run your scripts from the session2 folder, so open("movies.csv", "r") works directly.
If you run from the bda root folder instead, use open("session2/movies.csv", "r").
Let's create our first script. File: session2/solutions/exercise-02-01.py
import csv
with open("movies.csv", "r") as file:
reader = csv.DictReader(file)
for row in reader:
print(row)Expected output shape:
{'movie_id': '1', 'title': 'Movie 1', 'year': '2020', ...}
{'movie_id': '2', 'title': 'Movie 2', 'year': '1994', ...}Tip
What are the time and space complexities of this script?
Show answer
Time: O(n)
Space: O(1)
File: session2/solutions/exercise-02-01.py
import csv
with open("movies.csv", "r") as file:
reader = csv.DictReader(file)
for row in reader:
print(row["genres"])Expected output shape:
Romance
Action,
Animation,
Thriller
...Tip
What are the time and space complexities of this script?
Show answer
Time: O(n)
Space: O(1)
Count how many rows are from 2020. Complete the missing code.
File: session2/solutions/exercise-02-01.py
import csv
count = 0
with open("movies.csv", "r") as file:
reader = csv.DictReader(file)
...
print(count)Tip
Show solution
...
for row in reader:
if row["year"] == "2020":
count += 1
...Find the first row where genres contains Action. Fill up the missing code.
File: session2/solutions/exercise-02-01.py
import csv
with open("movies.csv", "r") as file:
reader = csv.DictReader(file)
for row in reader:
...Tip
What are the time and space complexities of this script?
Show answer
Time: O(n) worst case
Space: O(1)
...
if "Action" in row["genres"]:
print(row)
break
...Call Stelios for a quick challenge question before moving to the exercise.
Add your answers to:
session2/solutions/exercise-02-01.pyUse the Birkbeck/movies dataset from Hugging Face.
- Examine the field names using
reader.fieldnames. Print the names. - Print only the first 5 data rows.
- Count how many movies are from the
USA. - Find and print the first movie where
genresis exactlyAction. - Find and print the first movie where
Actionappears insidegenres. - In one short comment, explain one benefit of
DictReaderovercsv.reader. - What are the time and space complexities of your script(s)?
Use the Birkbeck/movies_incomplete dataset from Hugging Face.
Download it into a separate folder so it does not overwrite movies.csv:
mkdir -p data/movies_incomplete
hf download Birkbeck/movies_incomplete movies.csv --repo-type dataset --local-dir data/movies_incomplete- Find the missing data point and print row and column.
- Find the average of
votesfromdata/movies_incomplete/movies.csv. Why does the naive script fail? How can you fix it?
Complete the following quiz.
quizmd quizzes/python-csv-dictreader-quiz.mdIf you want to choose a theme:
quizmd --theme light quizzes/python-csv-dictreader-quiz.md
quizmd --theme dark quizzes/python-csv-dictreader-quiz.md