Python lesson 20
Dictionaries. Labels, Not Numbers
A list remembers order. A dictionary remembers names.
Look It Up By Name
A dictionary stores pairs: a key and its value. You get a value back by asking for its key, not by counting positions. Curly braces make one, and square brackets look inside.
player = {"name": "Nova", "score": 40, "lives": 3}
player["score"] # 40
player["lives"] = 2 # change it
player["level"] = 1 # add a brand new one
player = {"name": "Nova", "score": 40, "lives": 3}
print(player["name"])
print(player["score"])
What Comes Out?
pet = {"name": "Rex", "legs": 4}
pet["legs"] = 3
print(pet["legs"])
Build a Player
A Whole Character Sheet
Run it, then change a value and run it again.
hero = {"name": "Echo", "power": "invisibility", "level": 3}
print(hero["name"], "has", hero["power"])
hero["level"] = hero["level"] + 1
print("Levelled up to", hero["level"])
Your Own Character
Change the name, the power and the level to make this character yours. Then add one new key of your own.
hero = {"name": "Echo", "power": "invisibility", "level": 3}
hero["pet"] = "dragon"
print(hero["name"], "the level", hero["level"], "hero")
print("Pet:", hero["pet"])
A Safe Lookup
Asking for a key that does not exist is an error. .get() hands back a fallback instead of crashing.
player = {"name": "Nova", "score": 40}
print(player.get("score", 0))
print(player.get("lives", 3))
What you can do on CodeIt
Run the example, change one part, and use the result to check your understanding before moving to the next lesson.