Skip to content
Forge Learn/Core Collections
Browsing as a guest. Sign in to save your progress and earn XP as you complete chapters.

Dictionaries & Sets

6 min read

You'll learn to

  • -Create and use dictionaries: access, get with a default, and iterate keys/values/items
  • -Use sets for fast membership testing and removing duplicates
  • -Build early intuition for why dict/set lookups feel instant compared to scanning a list

Lists and tuples are great when order matters and you look things up by position. A lot of real problems instead need lookup by name, like "what's this user's email" or "have I seen this ID before." That is exactly what dictionaries and sets are built for.

Dictionaries: Key-Value Pairs

Try it yourself

A dict maps keys to values. user["name"] does not mean "the item at position 0." It means "whatever value is stored under the key 'name'." Direct indexing (user["email"]) raises a KeyError if the key does not exist, which is why .get() is usually the safer choice when a key might be missing. It returns None (or a default you specify) instead of crashing. .items() is what you will reach for constantly when you need both the key and the value while looping.

Sets: Unique, Unordered Collections

Try it yourself

A set holds unique values with no guaranteed order. Adding a duplicate is silently a no-op rather than an error. The two things sets are best at are exactly what the example shows: checking "have I seen this before" with in, and collapsing a list down to its unique values by wrapping it in set(...).

Why in Feels Instant for Dicts and Sets

Here is a teaser worth sitting with, even before you have formally learned Big-O notation. That is coming soon, and it is the very next thing this course covers. Checking "is this value in my collection" with a list means Python may have to look at every single item, one at a time, until it finds a match or reaches the end. For a dict or a set, membership checks do not scan at all. Python computes where the value should be directly, so the check takes roughly the same tiny amount of time whether the collection has 10 items or 10 million.

That difference, scanning every item versus jumping straight to the answer, is the first real taste of algorithmic efficiency in this course. Phase 2 gives it a name (O(n) versus O(1)) and a rigorous way to reason about it. For now, the intuition is enough: prefer a set or dict over a list when all you need is "does this exist," especially over a large collection.

Interview Signal is part of Pro

See a real weak answer next to a real strong one for this exact topic.

Quiz is part of Pro

Test what you just read with a short quiz, and bank the XP.