Holding many values at once — lists, tuples, sets and dictionaries — then reading and writing real files, up to and including CSV.
Programming for Data Science · University of the Philippines Cebu
Order, slices, sorting, and aliasing
Fixed records and uniqueness
Lookups, tallies and nested data
Read, clean, compute, write back
Every dataset (a CSV, a JSON file, a database row) has one of these structures underneath.
Read a CSV of grades and write back a per-section summary, as a complete program.
Week 2 covered a value, a choice, a function. Real data, however, comes in bulk: thousands of rows. This requires containers and a way to load them.
A container is a value that holds other values — one variable, many items inside.
Lists and dictionaries do most of the work; tuples and sets fill two specific gaps.
Loading data in from a file instead of typing it into cells.
A compiler reads and writes values separated by commas.
“Comma-separated value” appears in a spreadsheet manual.
Added to the standard library in Python 2.3.
The first written standard, and the official text/csv file type.
Until 2005 CSV had no written standard, so programs still differ on details such as quoting and line endings.
A file format is an agreed way of writing data into a file so that another program can read it back.
Almost all spreadsheets and databases can import and export CSV.
Local, regional and national open-data portals publish standardised CSV files.
The DPWH flood-control dataset used in this course is a CSV file.
Its weakness, covered in week 9, is that a CSV stores only text: every number and date must be guessed when the file is read.
csv; no install neededSourceWikipedia: Comma-separated values; course dataset: DPWH flood control projects, CC0, n = 34,079
In Week 2, each variable held one value: a number, a string, a boolean. This week’s terms concern containers (values that hold other values) and about reading data from files.
An ordered collection of values in square brackets. It can be changed later.
e.g. [3, 5, 4]
An item’s position number, counted from 0. Analogy: seat numbers starting at zero.
e.g. in ["a", "b"], "b" is at index 1
A run of items taken by position: from the start index up to, not including, the stop.
e.g. [10, 20, 30][0:2] is [10, 20]
A function that belongs to a value, called with a dot after the value.
e.g. names.append("Ana")
An ordered collection in round brackets that cannot be changed once made.
e.g. a coordinate (10.3, 123.9)
An unordered collection in curly brackets that keeps only one of each value.
e.g. set(["yes", "no", "yes"]) is {'yes', 'no'}
A collection of key → value pairs. Analogy: a phone book maps a name to a number.
e.g. {"Cebu": 964000, "Davao": 1777000}
The label used to look up a value in a dictionary. Each key appears once.
e.g. pop["Cebu"] uses the key "Cebu"
The address of a file on disk. A bare name means “in the current folder”.
e.g. "grades.csv" or "data/grades.csv"
A plain-text table: one row per line, commas between the columns, often a header row first.
e.g. name,score then Ana,88
Ordered collections accessed by position.
Lists appeared briefly in Week 2’s loops. This part covers access by position, slicing and sorting, and one common error: aliasing.
0A list is an ordered collection of values in square
brackets. Each item has an index: its position number. The first item is
[0], not [1]. Negative indexes count from the end, so [-1]
is always the last item.
cities = [...]a list of four strings, stored under the name citiescities[0]square brackets after a list mean “the item at this index”: "Cebu"cities[-1]count from the end: the last item, "Baguio"len(cities)how many items: 4. So the last index is 4 - 1 = 3A slice like cities[1:3] takes from the
start index up to but not including the stop index — here, Davao and Iloilo.
The list is a row of
seats numbered from 0. cities[2] means “whoever sits in seat 2”;
cities[1:3] means “everyone from seat 1 up to, but not including, seat 3”.
[1:3] gives two items, not three, because the stop is exclusive.
Index 0 is the first item; index −1 is the last.
cities[1] and cities[-2] are.cities[1] to cities[4]. What does the error say?Result on the lecture laptop (select to reveal)
Davao Iloilo. cities[4] stops with IndexError: list index out of range: four cities have indexes 0 to 3.
| Operation | Code | Result on [3, 5] |
|---|---|---|
| Add to the end | nums.append(9) | [3, 5, 9] |
| How many | len(nums) | 2 |
| Membership test | 5 in nums | True |
| Sum them | sum(nums) | 8 |
| Visit each item | for n in nums: | 3, then 5 |
These five cover most list work. for n in
nums gives the values, not the positions. .append is
a method: a function that belongs to a value, called with a dot after it.
5 in nums tests whether 5 is one of the items and gives True or
False.
Week 2's running-total loop followed this pattern: go through a list and accumulate.
b = a does not copy the list — it gives the
same list a second name, an alias. A change through either name
affects "both", because there is only one list.
b = a is a second key to the same house, not a
second house; moving furniture with either key changes the one house.
.copy() builds a second house.
An independent copy must be requested explicitly: .copy() (or list(a)).
sorted() returns; .sort() rearrangesTwo tools with one important difference: sorted(x) hands back a
new sorted list; x.sort() reorders the original
in place (it changes the list itself rather than making a new one) and
returns None.
x = x.sort() sets x to None. Only one of the two tools
should be used at a time.
sorted(temps)a new list, smallest to largest; temps itself is untouchedreverse=Truea keyword argument: sort largest first instead[:2]slice with no start = “from the beginning”: the first two items, i.e. the top twosplit separates; join combinesA line of text becomes a list of pieces with .split(); a list
becomes one string with .join(). This pair connects files and containers,
and is used again in Part D.
split is called on the string; join on the
separator (the text placed between pieces, here "," or
" | "). This is a frequent source of error. The quotes in '964000' say it is
still a string.
split returns text, even for the digits.
parts[1] * 2 prints.int(parts[1]) * 2. Predict, then run.Result on the lecture laptop (select to reveal)
964000964000: text times 2 repeats it. With int(...) it doubles the number: 1928000.
Given nums = [10, 20, 30, 40],
what does nums[1:3] return?
[10, 20, 30][20, 30][20, 30, 40][10, 20]B — [20, 30].
Start at index 1 (20), stop
before index 3 (40). The stop index is never included, so the
slice has 3 − 1 = 2 items.
Slice length is stop − start. This arithmetic gives the item
count directly.
The stop index is always exclusive.
Two smaller containers, each with one specific purpose.
Part A covered lists: ordered and changeable. Each container in this part deliberately omits one list feature — a tuple cannot change; a set has no order and no duplicates.
A tuple uses round brackets instead of square. Indexing and slicing work exactly as for a list, but it is immutable (cannot be changed after it is made), so any attempt to modify it raises an error. This rigidity is intentional.
TypeError: this type (a tuple) does not allow that operationpoint[0] = …Fixed-shape records: a coordinate, an (R, G, B) colour, a (name, score) pair. Each position has a fixed meaning.
Unpacking: assign a tuple to comma-separated names and
Python hands out the values in order — the first to lat, the second to
lon. This is used throughout Part C: a dictionary’s
.items() gives (key, value) tuples. (tally below is
the vote-count dictionary built in Part C.)
Two names need exactly two values — otherwise
ValueError: too many/not enough values to unpack. A ValueError means
the type was right but the value did not fit (here: the wrong number of items).
A set: curly brackets, no duplicates, no positions. It is the preferred tool for two tasks: dedup (removing duplicates) and fast membership tests (checking whether a value is present).
set(votes)make a set from the list: each answer kept once. No index, so the order may varylen(set(votes))how many different answers: 2"maybe" in set(votes)whether "maybe" is one of them: FalseThe number of distinct cities in a column is
len(set(column)), in one line.
| Question | Operator | {1,2,3} vs {3,4} |
|---|---|---|
| In either group (union) | A | B | {1, 2, 3, 4} |
| In both groups (intersection) | A & B | {3} |
| In A but not B (difference) | A - B | {1, 2} |
The students who submitted the lab but not the quiz are
submitted_lab - submitted_quiz. Many data questions are set questions.
Membership (in) on a set is near-instant regardless of size; on a long
list it requires a full scan. For two overlapping circles, union is everything
in either circle, intersection the overlap, difference the
part of A outside B.
| Container | Looks like | Ordered | Changeable | Typical use |
|---|---|---|---|---|
| list | [1, 2, 2] | Yes | Yes | the items, in order |
| tuple | (10.3, 123.9) | Yes | No | a fixed-shape record |
| set | {1, 2} | No | Yes | uniqueness & membership |
| dict | {"a": 1} | Insertion | Yes | lookup by name |
Ninety percent of programs use lists and dicts; tuples and sets are the right tool often enough to be worth knowing.
A DataFrame (pandas’ table, Week 6) column behaves like a list; a row like a dict; its row labels like a set. These four are the basic components. “Changeable” is also called mutable; “Insertion” means items stay in the order in which they were added.
A column of 500 barangay names has duplicates. Which expression counts the distinct barangays?
len(names)len(set(names))set(len(names))sorted(names)[0]B — len(set(names)).
set() collapses duplicates;
len() counts what remains. A gives 500 (rows, not barangays); C is
reversed and errors; D is only the alphabetically first name.
Read compound expressions inside-out: set(names) first, then
len(...) of that.
Distinct count = len(set(x)). This is used weekly.
Next: dictionaries, nested data and real files.
Values accessed by key, not by position.
Lists and tuples find things by position. This part adds the dictionary, which finds things by name and then places containers inside containers, which is the structure of real datasets.
When "the third item" is meaningless but "Davao's population" is the required value, a dictionary is appropriate. Each entry is a key : value pair: the key is the label that is looked up, the value is what is returned.
A phone book, where a name (the key) is looked up to find a number (the value), not “the 3rd entry”.
pop = { … }curly brackets with key: value pairs make a dictionary964_000the underscores are only for human readers: Python reads 964000pop["Davao"]look up the value stored under the key "Davao": 1777000pop["Baguio"] = 366_000a new key: adds the pair. (An existing key would be overwritten.)“A mapping object maps hashable values to arbitrary objects.” The dictionary is Python’s standard mapping type.
| Part of the definition | In pop |
|---|---|
| hashable values: the keys, each unique | "Cebu", "Davao", "Baguio" |
| arbitrary objects: the values | 964000, 1777000, 366000 |
| maps: one value per key, found by the key | pop["Davao"] gives 1777000; no position needed |
Source: Python Standard Library documentation, “Mapping Types — dict”.
| List | Dictionary | |
|---|---|---|
| Reach an item by | position: x[0] | key: x["Cebu"] |
| Order significant | Yes; it is a sequence | Insertion order kept, rarely used |
| Best when | "the items, in order" | "look this up by name" |
| Missing item | IndexError | KeyError (or .get) |
A list suits data where order matters; a dictionary suits lookup by a meaningful name.
A spreadsheet row is often a dict; a whole column is often a list.
[] raises an error; .get() returns a defaultRequesting a missing key raises KeyError. When gaps are
expected, as in most real data, .get() returns a default
instead.
KeyError: 'Manila' — the dictionary has no key 'Manila'; the message is the missing key"manila" and "Manila" are different keys.get(key, default)None) instead of stoppingA dictionary maps each distinct item to a running count. This pattern underlies word counts, vote counts and category frequencies.
tally = {}start with an empty dictionaryfor v in votes:one pass per vote; v is "yes", then "no"…tally.get(v, 0) + 1the count so far for this vote (0 if it is new), plus onetally[v] = …store the new count under that key{'yes': 3, 'no': 1}the result: three yes votes, one noThe same counting loop, on six votes with a new answer in them.
"maybe" to the list twice. What changes in the output?Result on the lecture laptop (select to reveal)
{'yes': 3, 'no': 2, 'abstain': 1}. With two "maybe" a fourth key appears, 'maybe': 2: the loop needs no change.
| Loop | Gives | Use when |
|---|---|---|
for k in d: | each key | only the labels are needed |
for v in d.values(): | each value | only the numbers are needed |
for k, v in d.items(): | both at once | the pair is needed (the common case) |
.items() is the most used: it gives the key and its value
together as a tuple, unpacked into k, v.
Plain for k in d gives keys, not values.
A loop for x in scores: runs over a
dictionary scores. What does x hold each time?
(key, value) pairsB — the keys.
Looping a dict directly gives its
keys. For the values use .values(); for both use
.items(). Assuming the loop gives values is a very common bug.
Values must be requested explicitly: d[k] inside the loop, or
.items().
Bare loop over a dict → keys.
Nested data is a container inside a container. List of dicts = one dict per row. Dict of lists = one list per group or column. Every CSV, every JSON response (a common text format for web data, Week 9) and every DataFrame has one of these two structures.
DS 227's scraper builds a list of dicts, then pd.DataFrame(rows). The
structure and the reason are the same.
Each bracket removes one layer. students[0] is a dict;
["name"] reaches into it. Chains are read left to right, one layer at a time.
A postal address, first the building (students[0]),
then the room inside it (["name"]).
For deeply nested data, print one layer at a time: print(x), then
print(x[0]), then print(x[0]["name"]).
Loop over the rows; each pass holds one dict. Every filter, tally and maximum question is a variant of this loop. (The grey lines show what the variables hold afterwards.)
for s in students:s is one student’s dict each time rounds["score"] >= 80whether that student’s score is at least 80top = students[0]start by assuming the first student is the besttop = sa higher score was found: store this student insteadAn extension of the tally pattern: instead of counting per key, values are collected per key. A new key starts an empty list; values are then appended.
pandas' df.groupby("section") performs this loop
internally.
if sec not in by_section:checks whether this section is new (in on a dict checks its keys)by_section[sec] = []then give it an empty list to fillby_section[sec].append(…)add this student’s score to their section’s listReading data from disk instead of typing it into a cell.
So far every value was typed into the code. Parts A–C covered containers; this part fills them from files on disk and writes results back out.
A file is named data saved on disk; its
file path is its address. "hours.txt" alone means
“in the current folder”; "data/hours.txt" means “inside the
data folder”. A loop over an open file gives one line per pass. The
with block closes the file automatically when it ends, even
if an error occurs.
open("hours.txt")open the file for reading; a wrong path gives FileNotFoundErrorwith … as f:call the open file f inside the indented block; close it at the endfor line in f:one line of text per pass — always a stringrepr(line)show the string with its hidden characters: \n is the end-of-line mark\nEach line carries an invisible newline character,
written \n: the mark that says “the line ends here”. repr()
reveals it. If it is left in, comparisons and conversions fail without visible cause.
.strip() removes whitespace (spaces, tabs, newlines) from both ends.
Apply .strip() to every line when reading. Whitespace should be removed before
the text is used.
Strip each line, convert it to a number, accumulate. This short loop is the basic structure of every data-loading script.
total = count = 0start both at 0 in one lineif not line: continuean empty string is falsy; continue = skip the rest of this pass, go to the next linetotal += int(line)turn the text into a number and add it (+= means total = total + …)print(total / count)the average of the non-blank linesif not line: continue — an empty string is "falsy," so this skips them.
.strip() removes leading/trailing spaces, tabs and the newline.
A 0 may be a real reading or missing data. The file does not say; the
analyst must decide.
Loading a file involves a sequence of small decisions, as in DS 227's Data Preparation phase.
"The default is a choice" applies here too: each irregularity is deliberately skipped, kept or flagged.
"w" and its riskOpen with a mode string, which states the intended
operation: "r" reads (the default), "w" erases and rewrites
the file; "a" appends to the end. Newlines must be added explicitly; write()
does not add them.
open("data.txt", "w") empties the file the instant it runs —
before any write. Raw data files should never be opened in "w".
splitReal data files have several values per line, separated by commas: a
CSV file (comma-separated values). The first line is usually the
header row — the column names. Part A's .split(",")
turns each line into a list — a row.
Each record is on a separate line. Fields are separated by commas. Fields containing line breaks, double quotes or commas should be enclosed in double quotes.
| Line | Fields, by the rules |
|---|---|
Ana,A,88 | 3: Ana, A, 88 |
"Reyes, Jr.",A,90 | 3: the quoted Reyes, Jr. keeps its comma |
split(",") knows only the second rule; the csv module follows all three, as the next slide shows.
Source: Shafranovich (2005), RFC 4180: Common Format and MIME Type for Comma-Separated Values (CSV) Files, IETF.
split(",") fails on real CSVsWhen a value itself contains a comma, simple splitting breaks the
row apart. CSV’s quoting rule: a value containing a comma is wrapped in double quotes. The
csv module — a file of ready-made code that comes
with Python, loaded with import csv — knows all the rules.
next(...) takes the first row the reader produces.
split is adequate for self-written files. For any other CSV, use the
csv module.
csv.reader: each row arrives splitThe reader wraps the open file and yields rows as lists. next(reader)
removes the header row before the loop.
reader = csv.reader(f)wrap the open file: each row will come out as a list of stringsheader = next(reader)take the first row (the column names) off the topfor row in reader:the remaining rows, one list per passDictReader: rows accessed by nameIt uses the header row as keys, so each row is a dict —
row["score"] instead of row[2]. This is the list-of-dicts shape
from Part C, read directly from disk.
'88', not 88. CSV has no types, so
int(row["score"]) must be done explicitly.
list(csv.DictReader(f))read every row as a dict (header names as keys) and collect them in a listlen(rows) → 5five data rows; the header is not countedrows[0]the first row: a dict, so rows[0]["name"] is 'Ana'DictReader gives each row as a dictionary, so a column is read by its name.
80 to 90. Who is left?Result on the lecture laptop (select to reveal)
3: ['Ana', 'Carla', 'Diego']. With 90, only ['Carla'].
csv.writer handles the commas and quoting automatically: one
writerow per line, header first. w.writerow([...]) takes a list and
writes it as one comma-separated line. The grey block shows the resulting file contents.
newline="" argumentRequired when writing CSV; without it, Windows inserts blank lines between rows. It should always be included.
After rows =
list(csv.DictReader(f)), what is rows[0]["score"] + 2?
90'882'TypeError'88 + 2'C — TypeError: cannot add
str and int.
CSV values are always strings:
rows[0]["score"] is '88'. Conversion is required first:
int(rows[0]["score"]) + 2 → 90. (B would be the answer
for + "2" — string concatenation.)
Files provide text. Numbers exist only after explicit conversion.
Convert at the moment of reading — int(...)/float(...) right
in the loop.
Read a grades CSV → group scores by section → write a summary CSV. Containers, nesting and files in twelve lines.
DictReader loads rows; the grouping move collects scores per
section; csv.writer saves the answer. All three patterns appear below.
rows = list(csv.DictReader(f))1 · read: every row as a dictby_sec[sec].append(int(…))2 · group: each score, converted to a number, into its section’s listfor sec in sorted(by_sec):3 · write: the sections in order A, B (sorting a dict sorts its keys)round(… , 1)the mean, rounded to 1 decimal placeThis program was run when the deck was built. Input: 5 students, 2 sections. Output: one clean summary that another program (or Excel) can open.
Section A: (88 + 91 + 67) / 3 = 82.0. A pipeline should be spot-checked by hand at least once.
The lab covers slicing and sorting a list, unpack a tuple, count distinct values with a set, tally votes and group scores in a dictionary, write a small file and read it back, then read a CSV and average it per section — the full load-and-summarise loop. ~45 minutes.
How it works: replace each ____, press
▶ Run, then Check. Each part starts with a short
reminder of the terms it uses.
Indexing and slicing, .get() lookups, the tally pattern, and
with open(...).
Re-run this week's worked example on a new CSV, change a score and observe the summary.
Then add a count column per section.
Slices exclude the stop; b = a aliases; tuples fix a record's shape.
.get() for safety; tally and grouping patterns;
len(set(x)) for distinct counts.
List of dicts = rows. Dict of lists = groups. Chain brackets outside → in.
with open, .strip(), csv.DictReader in,
csv.writer out.
Summary: load rows into containers, clean them while reading, group with a dict, and write the answer back out.
Build a complete file-in, file-out data program — no pandas required (yet).
All new terms from this week, one line each. pandas (Weeks 6–7) is built on all of them.
[3, 5, 4]-1 is the last itemx[start:stop]: from start up to, not including, stopx.append(9)b = a copies nothing(10.3, 123.9)lat, lon = point{1, 2}"grades.csv", "data/grades.csv""r" read, "w" erase and write, "a" add to the end\n that ends each line.strip()continueimport: csvimport csvFinish the Week 3 lab and submit it. The file-reading part should be reproducible from memory; then repeat the worked example unaided.
Socratica — Python Lists (a short lecture) and Corey Schafer — Lists, Tuples & Sets.
Python Tutorial §5 (lists, tuples, sets, dicts) and §7.2 (reading and writing
files); csv module intro — docs.python.org/3.
Everything here is linked on the course page beside this deck.
Organising larger programs with classes, errors and project layout.
Classes, errors and code organisation: keeping a program readable once it grows beyond a single notebook cell.
DS 208 · Programming for Data Science