Dictionaries
Data structures5 min readLesson 2 of 3
Minutes: 5
A dictionary maps keys to values. Lookup by key does not scan the items.
python
student = {"name": "Ada", "score": 92}
student["score"] # 92
student["grade"] = "A" # add a new key
student.get("email", "not set")get is the safe read: a missing key returns the default instead of raising. [] raises KeyError, which is useful when a missing key really is a bug.
Iterating gives keys by default; ask for what you need:
python
for key in student: ...
for key, value in student.items(): ...Counting is the classic use:
python
counts = {}
for word in ["a", "b", "a"]:
counts[word] = counts.get(word, 0) + 1Dicts keep insertion order, and since Python 3.7 that order is guaranteed by the language.
