Kids Coding
Dictionaries
A dictionary maps a key to a value. Store a score, a name, or a fact.
KidsIntermediateDictionaries
A label for each value
A list is ordered. A dictionary maps a key to a value. You look things up by name, not by position.
A player
player = {
"name": "Sam",
"score": 12,
}
print(player["name"])
print(player["score"])A list finds things by position (scores[0]); a dictionary finds them by name (scores["Sam"]). Pick the one that matches how you picture the data.
Change a value
Add points
player = {"name": "Sam", "score": 12}
player["score"] = player["score"] + 5
print(player["name"], "has", player["score"])Keys you have
in
player = {"name": "Sam", "score": 12}
if "score" in player:
print("Score is recorded")Real life
A contact in a phone: name, and a number.
You look up “Mum”, not “item 2”. A dict looks up by the label.
Phone contact
mum = {"name": "Mum", "number": "555-0142"}
print("Call", mum["name"])
print(mum["number"])
mum["number"] = "555-0199"
print("New number:", mum["number"])Change one word. Run it. That is how this idea shows up outside the lesson.
Try it
Exercise 1: Make a dict with title and pages. Print the title.
Show solution
book = {"title": "Foxes", "pages": 80}
print(book["title"])