Collections¶
One household is a handful of values; a barangay is hundreds of households. Python keeps many values together in collections. This module covers the four you will use every day, and how a barangay's records fit in them: a list of households, each one a dictionary of its values.
| section | what you do |
|---|---|
| 1 · Lists | an ordered row of values: take one, take a slice, change them, sort them |
| 2 · Tuples and sets | values that stay together, and values without repeats |
| 3 · Dictionaries, and records | values by name: one household as one dictionary |
import course
from course import check_cases, try_it
course.quizzes_at("3.0")
1 · Lists¶
A list holds values in order, between square brackets. It can hold any values, and the same value more than once.
crops = ["Palay", "Corn", "Coconut", "Mango"]
crops
['Palay', 'Corn', 'Coconut', 'Mango']
Taking one value. Each value has a position, its index, counted from 0: crops[0] is the first, crops[1] the second. A negative index counts from the end: crops[-1] is the last.
crops[0], crops[1], crops[-1]
('Palay', 'Corn', 'Mango')
Taking a slice. crops[start:stop] gives a new list from start up to, but not including, stop. Leave start out to begin at the beginning, stop out to go to the end.
crops[1:3], crops[:2], crops[2:]
(['Corn', 'Coconut'], ['Palay', 'Corn'], ['Coconut', 'Mango'])
len(...) counts the values, and in asks whether a value is there.
len(crops), "Corn" in crops, "Cassava" in crops
(4, True, False)
Changing a list. A list is mutable: it can be changed after it is made. crops[1] = ... replaces a value, .append(...) adds one at the end, .remove(...) takes out the first equal value.
crops = ["Palay", "Corn", "Coconut", "Mango"]
crops[1] = "Yellow corn"
crops.append("Cassava")
crops.remove("Mango")
crops
['Palay', 'Yellow corn', 'Coconut', 'Cassava']
Sorting. sorted(crops) gives back a new, sorted list and leaves crops as it was. crops.sort() sorts crops itself, and gives back nothing. Add reverse=True to either for the other order.
crops = ["Palay", "Corn", "Coconut", "Mango"]
in_order = sorted(crops)
crops, in_order, sorted([47, 18, 63, 35], reverse=True)
(['Palay', 'Corn', 'Coconut', 'Mango'], ['Coconut', 'Corn', 'Mango', 'Palay'], [63, 47, 35, 18])
Changing a list someone else is using. Two names can stand for the same list. Changing it through one name changes what the other sees:
planted = ["Palay", "Corn"]
this_season = planted # not a copy: the same list, with two names
this_season.append("Mango")
planted
['Palay', 'Corn', 'Mango']
planted gained "Mango" although the code only changed this_season. That is the most common surprise with lists. When a function is given a list, it should not change it unless that is its job: build a new list instead, with + (planted + ["Mango"]) or sorted(...), and give that back.
Exercise 3.1 · The oldest heads of household¶
Finish oldest(ages, n) so that it returns the n highest ages, from highest down, as a list. It must not change ages.
| call | returns |
|---|---|
oldest([47, 18, 63, 35, 52], 2) |
[63, 52] |
oldest([30, 30, 41], 3) |
[41, 30, 30] |
def oldest(ages, n):
# Step 1: sort the ages from highest to lowest, as a new list
# Step 2: return the first n of them
raise NotImplementedError("Exercise 3.1") # delete this line when your code is ready
try_it(oldest, [47, 18, 63, 35, 52], 2)
oldest([47, 18, 63, 35, 52], 2): not written yet. Write your code, delete the raise NotImplementedError line, and run the function's cell.
check_cases(
"Exercise 3.1", oldest,
[(f"oldest({a}, {n})", (a, n)) for a, n in [([47, 18, 63, 35, 52], 2), ([30, 30, 41], 3), ([25], 1), ([70, 20, 45, 60], 0), ([33, 81, 54], 5)]],
what="lists", hint="`sorted(..., reverse=True)`, then a slice.",
)
Exercise 3.1: not attempted yet. sorted(..., reverse=True), then a slice.
If the check is red: common causes for Exercise 3.1
- The lowest ages: the list is sorted from lowest up. Add
reverse=True. None:.sort()sorts in place and gives back nothing. Usesorted(...), which gives back the new list.- One age too many or too few: a slice
[:n]stops before positionn, so it already holds exactlynvalues.
Exercise 3.2 · Add a household without changing the list¶
The enumerators keep a sorted list of household IDs. Finish with_household(ids, new_id) so that it returns a new sorted list with new_id added, and leaves ids as it was. The cell after Try it says whether your function leaves the list it is given unchanged; the check after that, whether its results are right.
| call | returns |
|---|---|
with_household(["H001", "H004"], "H002") |
["H001", "H002", "H004"] |
def with_household(ids, new_id):
# Step 1: make a new list with new_id added (ids + [new_id] does not change ids)
# Step 2: return it sorted
raise NotImplementedError("Exercise 3.2") # delete this line when your code is ready
try_it(with_household, ["H001", "H004"], "H002")
with_household(['H001', 'H004'], 'H002'): not written yet. Write your code, delete the raise NotImplementedError line, and run the function's cell.
course.leaves_unchanged(with_household, ["H001", "H004"], "H002")
with_household is not written yet.
check_cases(
"Exercise 3.2", with_household,
[(f'with_household({i}, "{n}")', (i, n)) for i, n in [(["H001", "H004"], "H002"), ([], "H001"), (["H002", "H003"], "H001"), (["H010"], "H011")]],
what="lists", hint="Build a new list with `+`; do not `.append` to `ids`.",
)
Exercise 3.2: not attempted yet. Build a new list with +; do not .append to ids.
If the check is red: common causes for Exercise 3.2
- Green, but the cell above it is red: the result is right, but
idswas changed. Useids + [new_id]instead of.append. TypeError: can only concatenate list (not "str") to list: wrap the new ID in brackets,[new_id].- Not in order: return
sorted(...)of the new list.
2 · Tuples and sets¶
A tuple is like a list that cannot change, written with round brackets: ("Malanday", 7). Use one for values that belong together and stay together, such as a barangay's name and code. Unpacking gives each value of a tuple its own name in one line:
barangay = ("Malanday", 7, 1401)
name, code, population = barangay
name, population
('Malanday', 1401)
A function can return several values as one tuple: return lowest, highest, and whoever calls it unpacks them.
A set holds values without repeats and without order, in curly brackets. set(...) turns a list into one, which is the quickest way to find the distinct values in it. A set can change (.add(...)), but has no positions: there is no [0].
crops_reported = ["Palay", "Corn", "Palay", "Mango", "Corn", "Palay"]
distinct = set(crops_reported)
distinct, len(distinct), "Mango" in distinct
({'Corn', 'Mango', 'Palay'}, 3, True)
A set has no order, so to show its values in a fixed order, sort them: sorted(distinct) gives a list.
Exercise 3.3 · The crops a barangay grows¶
Each farming household reports its main crop. Finish distinct_crops(reported) so that it returns the crops reported, each once, in alphabetical order, as a list.
| call | returns |
|---|---|
distinct_crops(["Palay", "Corn", "Palay", "Mango"]) |
["Corn", "Mango", "Palay"] |
def distinct_crops(reported):
# Step 1: keep each crop once (a set)
# Step 2: return them as a sorted list
raise NotImplementedError("Exercise 3.3") # delete this line when your code is ready
try_it(distinct_crops, ["Palay", "Corn", "Palay", "Mango"])
distinct_crops(['Palay', 'Corn', 'Palay', 'Mango']): not written yet. Write your code, delete the raise NotImplementedError line, and run the function's cell.
check_cases(
"Exercise 3.3", distinct_crops,
[(f"distinct_crops({r})", (r,)) for r in [["Palay", "Corn", "Palay", "Mango"], [], ["Coconut"], ["Mango", "Mango", "Mango"], ["Corn", "Cassava", "Ampalaya", "Corn"]]],
what="lists", hint="`set(...)` then `sorted(...)`.",
)
Exercise 3.3: not attempted yet. set(...) then sorted(...).
If the check is red: common causes for Exercise 3.3
{...}in curly brackets: that is the set itself. Returnsorted(...)of it, which is a list.- Repeats in the result: the list was sorted, but never made into a set.
3 · Dictionaries, and records¶
A dictionary (dict) holds values by key instead of by position, in curly brackets with key: value pairs. One household of the barangay is one dictionary: each of its values has a name.
household = {"id": "H001", "barangay": "Malanday", "members": 5, "head_age": 47, "farms": True, "crop": "Palay"}
household["members"], household["barangay"]
(5, 'Malanday')
household["members"] gives the value of a key, and raises a KeyError when the key is not there. household.get("phone") gives None instead, and household.get("phone", "none given") the second value. "crop" in household asks whether a key is there.
household.get("phone"), household.get("phone", "none given"), "crop" in household
(None, 'none given', True)
A dictionary is mutable, like a list: household["members"] = 6 changes a value, or adds the key if it was not there. The same caution applies: a function given a record should build a new dictionary rather than change the one it was given. {**household, "members": 6} is a new dictionary with every key of household, and members set to 6.
grown = {**household, "members": 6}
household["members"], grown["members"]
(5, 6)
A barangay's records are then a list of dictionaries, one per household, all with the same keys. Modules 4 and 5 work through lists like this one, and module 6 reads the same records from a file.
households = [
{"id": "H001", "barangay": "Malanday", "members": 5, "head_age": 47, "farms": True, "crop": "Palay"},
{"id": "H002", "barangay": "Malanday", "members": 7, "head_age": 63, "farms": True, "crop": "Corn"},
{"id": "H003", "barangay": "Tumana", "members": 2, "head_age": 29, "farms": False, "crop": None},
]
households[1]["head_age"], len(households)
(63, 3)
Exercise 3.4 · One line about a household¶
Finish summary(record) so that it returns a line such as H001: 5 members in Malanday, from a household's dictionary.
| call | returns |
|---|---|
summary({"id": "H001", "barangay": "Malanday", "members": 5, ...}) |
"H001: 5 members in Malanday" |
def summary(record):
# Step 1: take the id, the members and the barangay from the dictionary by their keys
# Step 2: return them in one f-string
raise NotImplementedError("Exercise 3.4") # delete this line when your code is ready
try_it(summary, households[0])
summary({'id': 'H001', 'barangay': 'Malanday', 'members': 5, 'head_…): not written yet. Write your code, delete the raise NotImplementedError line, and run the function's cell.
check_cases("Exercise 3.4", summary, [(f'summary(households[{i}])', (h,)) for i, h in enumerate(households)], what="households",
hint="Take each value with `record[\"key\"]`.")
Exercise 3.4: not attempted yet. Take each value with record["key"].
If the check is red: common causes for Exercise 3.4
KeyError: a key is misspelt. The keys are"id","members"and"barangay", all lower case.NameError: name 'members' is not defined: the f-string uses{members}; inside the function the value isrecord["members"].
Exercise 3.5 · A corrected record¶
A revisit finds a household has a different number of members. Finish corrected(record, members) so that it returns a new dictionary, the same as record but with members changed, and leaves record as it was.
| call | returns |
|---|---|
corrected({"id": "H003", "members": 2, ...}, 3) |
{"id": "H003", "members": 3, ...} |
def corrected(record, members):
# Step 1: return a new dictionary with every key of record, and members set to the new value
raise NotImplementedError("Exercise 3.5") # delete this line when your code is ready
try_it(corrected, households[2], 3)
corrected({'id': 'H003', 'barangay': 'Tumana', 'members': 2, 'head_ag…, 3): not written yet. Write your code, delete the raise NotImplementedError line, and run the function's cell.
course.leaves_unchanged(corrected, households[2], 3)
corrected is not written yet.
check_cases(
"Exercise 3.5", corrected, [(f"corrected(households[{i}], {m})", (h, m)) for (i, h), m in zip(enumerate(households), [6, 8, 3])],
what="records", hint="`{**record, ...}` makes the new dictionary.",
)
Exercise 3.5: not attempted yet. {**record, ...} makes the new dictionary.
If the check is red: common causes for Exercise 3.5
- Green, but the cell above it is red: the result is right, but the record given was changed. Build a new dictionary with
{**record, "members": members}. - The old number of members:
"members": membersis written before**record, so the old value overwrites it. Put it after.
course.quizzes_at("3.3")
Next: Decisions and repetition, in 30_decisions.ipynb.