Skip to content
Dictionary Fundamentals
step 1/8

Reading — step 1 of 8

Learn

~3 min readDictionaries and Sets

Think about a phone book. You don't search it by position — you search by name: "What's Alice's number?" The name is the key, the number is the value. A Python dictionary (also called a dict) works exactly like this — it maps keys to values for instant lookup. No scanning a list, no sorting, no binary search. Behind the scenes, a dict uses a hash table — average-case O(1) access regardless of size.

Dicts are arguably the most useful data structure in Python. Counting word frequencies, caching computed results, mapping IDs to records, configuration options, JSON data — they all come back to dicts.

Creating dictionaries

python

A dict literal uses curly braces with key: value pairs separated by commas.

Accessing values

python
  • dict[key] — fast, but raises KeyError if missing.
  • dict.get(key) — returns None if missing.
  • dict.get(key, default) — returns default if missing.

Use .get() whenever the key MIGHT be missing and missing is OK.

Membership and length

python

Note: in checks keys, not values. To check values: "Alice" in student.values().

Adding, updating, removing

python

Iterating

Three ways, picked by what you need:

python

.items() gives you tuples — almost always what you want when working with both.

Key requirements

Dict keys must be hashable (immutable). Strings, ints, floats, tuples (of hashables), and frozenset work. Lists, sets, and dicts DO NOT — they're mutable.

python

Values can be anything. (Yes, even other dicts — you'll see this with JSON.)

Insertion order is preserved

Since Python 3.7, dicts remember insertion order:

python

This matters when you serialize to JSON or print results — predictable order.

Worked example: word frequency

The dict + counting pattern is everywhere:

python

The .get(word, 0) returns 0 for new words, then we add 1 and store. Idiomatic and concise.

(For heavy counting work, collections.Counter is even cleaner — covered in Dictionary Techniques.)

Common mistakes

  • d[key] for missing keys raises KeyError. Use .get() or key in d first.
  • Iterating with .items() and forgetting unpacking: for x in d.items(): print(x[0]) works but for k, v in d.items() is cleaner.
  • Trying to use a list as a key: d[[1,2]] = ... is TypeError. Use a tuple d[(1,2)].
  • Mutating a dict while iterating it: raises RuntimeError in modern Python. Iterate over list(d) if you need to delete keys.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…