Sign in

Intro to Computer Science / Unit 8: Lists and Data

8.5 Dictionaries

3 practice questionsNot yet reviewed

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, then 3 after adding a new key.
  • key in ages checks 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?
With d = {"x": 5}, what does print(d.get("y", 0)) display?
A program must store each student's name with that student's grade and find a grade by name. Which structure fits best?

Ready for more? Take the Unit 8 test.