Intro to Computer Science / Unit 8: Lists and Data
8.5 Dictionaries
Notes
A dictionary stores key: value pairs inside curly braces. You look up a value by its key.
ages = {"Ana": 15, "Ben": 16}
print(ages["Ana"])
ages["Cy"] = 14
print(len(ages))
- This prints
15, then3after adding a new key. key in ageschecks for a key.ages.get("Zed", 0)returns 0 if the key is missing instead of an error.- Looking up a missing key with square brackets causes a
KeyError. - Keys must be unique. Use
for key in ages:to loop through the keys. - Use a dictionary when you look up by a name or label; use a list when order and position matter.
Practice
With
d = {"a": 1, "b": 2}, what does print(d["b"]) display?The key "b" maps to the value 2.
With
d = {"x": 5}, what does print(d.get("y", 0)) display?get returns the default value 0 when the key is missing.
A program must store each student's name with that student's grade and find a grade by name. Which structure fits best?
A dictionary maps names (keys) to grades (values) for quick lookup.
Ready for more? Take the Unit 8 test.