Data Structures · Dictionaries and Sets · lesson 6 of 10
Dictionary basics
about 12 minutes · free · runs in your browser
Step 1 of 2
Looking up by name
A dictionary stores pairs: a key, and the value it points at. Written with braces:
person = {"name": "Ada", "age": 36, "city": "London"}
You look things up by key rather than position:
person["name"] # "Ada"
person["age"] = 37 # change it
person["job"] = "Mathematician" # add a new pair
Asking for a key that is not there raises KeyError. .get() is the safe version:
person.get("job") # None if missing
person.get("job", "unknown") # your own fallback
Keys are usually strings, but any immutable value works. Values can be anything at all, including other dictionaries.
Your turn: add a "country" of "UK", change the age to 37, and safely read a
"job" that may not be there, defaulting to "unknown".
You start from this, and edit it in the browser:
person = {"name": "Ada", "age": 36, "city": "London"}
# Add country, update age, and read job safely into job.
Step 2 of 2
Counting with a dictionary
Counting occurrences is the classic dictionary job:
counts = {}
for word in words:
counts[word] = counts.get(word, 0) + 1
counts.get(word, 0) gives the count so far, or zero the first time — which avoids
having to check whether the key exists.
Your turn: write count_letters(text) returning a dictionary of how many times each
character appears.
You start from this, and edit it in the browser:
def count_letters(text):
# Return {character: count}
pass