~/learn/Python · Collections

Sets and dictionaries

Membership tests and key-value lookups.

7 min readlesson 10 of 23dictsetcounting

why this matters

Dictionaries let you look things up by name instantly — like a price list. Sets remove duplicates in one step.

A set holds unique, unordered values and tests membership in constant time. It also supports mathematical operations.

python · editable
loading editor…

A dict maps keys to values. Use .get for a safe lookup with a default, and .items() to loop over pairs.

python · editable
loading editor…

Counting occurrences is the classic dict pattern, and a dict comprehension builds one in a single line.

python · editable
loading editor…

Pro tip

Use d.get(key, default) instead of d[key] when the key might be missing — it won't crash.

key takeaways

  • dict maps keys → values.
  • set keeps unique items only.
  • Lookups in both are very fast.

check your understanding

prices = {"tea": 2}. What does prices.get("coffee", 0) return?

free practice

Build confidence with a question you can solve without Pro.