Skip to content
dreamcode
dreamcode
Map
Dict methods
Lesson 29 of 77
+15 XP on finish
COLLECTIONSChapter 5 · Collections

Dictionary methods

.get(key, default) reads a value without crashing when the key is missing. .keys(), .values() and .items() let you loop over a dictionary, and .items() gives you each key and value together. .update(other) merges another dict in, and .pop(key) removes an entry and returns its value.

Worked example

How it reads

  • .get("color", "unknown") falls back to the default instead of raising KeyError
  • .update adds new keys and overwrites existing ones
  • for key, value in star.items() unpacks each pair
Common mistakes
  • d["missing"] raises KeyError. Use d.get("missing") when a key might not be there.
  • Adding or removing keys while looping over the same dict raises RuntimeError. Loop over list(d.items()) instead.
Cloud tip: Counting things? counts[word] = counts.get(word, 0) + 1 is the classic one-liner.
main.py
PYTHON
real Python, runs in your browser
Console
Run your code to see its output here.
YOUR TURN

Loop over votes.items() and print one line per star in the form Vega: 3.

Press Run to check your work.