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
- A dictionary maps keys to values:
ages = {"Ana": 19, "Ben": 20}. Look up withages["Ana"], add or change withages["Cy"] = 18, remove withdel ages["Ben"]orpop. - A missing key raises
KeyError;ages.get("Zed", 0)returns a default instead."Ana" in agestests keys, not values. - Loop over
ages(keys),ages.values()orages.items()for key–value pairs.sorted(ages)gives the keys in order. - The counting pattern:
counts[word] = counts.get(word, 0) + 1. Grouping: a dictionary whose values are lists. - Keys must be immutable (strings, numbers, tuples). Values can be anything, including lists and other dictionaries.
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 3Grouping 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']}
CyWorked 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
d[key]on a missing key crashes; usegetor check withinfirst.- Assuming
inlooks at values. - Trying to use a list as a key (TypeError: unhashable).
- Looping with
for k, v in d:instead ofd.items().
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.