Python · The language, not just syntax

How do Python dictionaries work and when do you use them?

Easydicthash tablelookupUpdated Oct 2026
Quiz this track

Short answer

A dict is a hash table mapping hashable keys to values with average O(1) lookup, insertion and deletion. Since Python 3.7 it preserves insertion order, which makes it useful for ordered mappings and counters.

A dictionary stores entries in a compact array and uses a hash index to find a slot. Key equality is checked with == after hashing, so keys need consistent __hash__ and __eq__ implementations. Average operations are O(1), but a poor hash or heavy collisions can degrade performance.

python
counts = {}
for word in ["a", "b", "a"]:
    counts[word] = counts.get(word, 0) + 1

counts.setdefault("c", 0)

for key, value in counts.items():
    print(key, value)
get and setdefault avoid a KeyError. Iterating items gives keys and values without a second lookup.

Idioms worth knowing

  • Use d.get(key, default) instead of try/except when a missing key is normal
  • Use collections.defaultdict when every access should create a default
  • Use dict comprehension for transforms: {k: v for k, v in pairs}
  • Use d | other or {a, b} to merge, with the right-hand side winning

Because keys must be hashable, mutable objects such as lists cannot be keys. Insertion order is guaranteed by the language since 3.7, but equality ignores order: two dicts with the same pairs are equal regardless of when the keys were inserted.

Mutating a dictionary while iterating over it raises RuntimeError. Iterate over list(d) or build a separate collection when you need to delete or add entries.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1What makes a valid dictionary key?
  2. 2What is the complexity of a dict lookup and when does it degrade?
  3. 3Does dict equality consider insertion order?
  4. 4What is the difference between defaultdict and setdefault?

Say it in the interview

A dict is a hash table that maps hashable keys to values. Lookups, inserts and deletes are O(1) on average, and insertion order is preserved as a language guarantee. I use get or setdefault for optional keys and defaultdict when a default should be created automatically. I also avoid mutating a dict while iterating it, and I remember that equality ignores insertion order.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Python mock interview and get scored feedback on depth, clarity and confidence.