MathubLearn / Practice / Excel
CSCI 127 Joy and Beauty of Data · Unit 2: Data structures · on Exam 2

2.3 Dictionaries

Study notes for Dictionaries in CSCI 127 Joy and Beauty of Data at Montana State University: the big ideas, code you should know, a worked example, common mistakes and an exam tip. The same topic has endless practice questions and flashcards in Mathub.

Big ideas

Code you should know

Lookup, update, iterate
ages = {"Ana": 19, "Ben": 20}
ages["Cy"] = 18
ages["Ana"] += 1
print(ages["Ana"], len(ages), "Ben" in ages, 20 in ages)
print(ages.get("Zed", "unknown"))
for name in sorted(ages):
    print(name, ages[name])
for name, age in ages.items():
    if age >= 20:
        print(name, "is 20+")
Output
20 3 True False
unknown
Ana 20
Ben 20
Cy 18
Ana is 20+
Ben is 20+
Word counts
text = "the cat and the hat and the bat"
counts = {}
for word in text.split():
    counts[word] = counts.get(word, 0) + 1
print(counts)
best = max(counts, key=counts.get)
print(best, counts[best])
Output
{'the': 3, 'cat': 1, 'and': 2, 'hat': 1, 'bat': 1}
the 3
Grouping into lists
pairs = [("math", "Ana"), ("cs", "Ben"), ("math", "Cy")]
by_class = {}
for subject, name in pairs:
    if subject not in by_class:
        by_class[subject] = []
    by_class[subject].append(name)
print(by_class)
print(by_class["math"][1])
Output
{'math': ['Ana', 'Cy'], 'cs': ['Ben']}
Cy

Worked example

What does this print?
d = {"a": 1, "b": 2}
d["c"] = d["a"] + d["b"]
d["a"] = 10
print(len(d), d["c"], sorted(d.values()))
Show the solution
3 3 [2, 3, 10]. c was computed as 1 + 2 before a changed; changing a later does not recompute c.

Common mistakes

Exam tipWrite the counting pattern from memory until it is automatic; it appears in labs, programs and on Exam 2.

Keep going in Mathub

Mathub is free for Montana State students: an endless quizzer with worked explanations, one-question lessons, flashcards, exam prep checklists, the class calendar with every deadline, a grade calculator and a study board for CSCI 127.