Home / Python Fundamentals

Dictionary Lab

Visualizing Python's Hash Map implementation. Experience the power of O(1) lookups and nested JSON-like structures.

Operations

Strings, numbers, lists, or dicts allowed.


Snippet


                    

Data State

my_dict = { ... }
items: 3
Modify keys above or click rows to pop elements.

Logic Insight

Dictionaries map unique keys to values using a hashing function for instant access.

  • • Key Type: Keys must be immutable (strings, numbers, tuples).
  • • Collision: Python handles hashing collisions internally to maintain speed.
  • • Search: Lookups don't scan the list; they calculate the address.

Performance Bar

Current Operation O(1)

Note: .keys(), .values(), and .items() take O(n).

Overview

For d[key], Python hashes the key to find a candidate slot, then checks equality to resolve collisions. Lookup and insertion are average O(1), but can take O(n) in the worst case. Iterating a dictionary takes O(n) time and follows insertion order, a language guarantee since Python 3.7.

Look up by key

Use Method, Key, and Value in the visualizer, then press Execute. Compare a lookup of a present key with a missing one: direct indexing raises KeyError when the key is absent.

Choose how to handle a missing key

d = {"apples": 3}

d["pears"]                 # raises KeyError
d.get("pears", 0)          # returns 0 without inserting
d.setdefault("pears", 0)   # returns 0 and inserts the key

Use get when a default is needed without mutation. Use setdefault when creating a missing entry is intended. For counting or grouping, collections.Counter and defaultdict often express the operation more clearly.

Membership checks keys: "apples" in d is average O(1). Checking "apples" in d.values() scans values and takes O(n). d.keys(), d.values(), and d.items() return dynamic views; creating a view is constant-time, iterating it is linear.

Keys must be hashable

Keys need a stable hash and equality behavior. Strings, numbers, and tuples of hashable values can be keys; lists and dictionaries cannot. A tuple containing a list is also unhashable. A custom type that defines equality must keep its hash consistent with that equality; mutating hash-relevant state after insertion can make a key impossible to find.

counts = {}
for word in ["red", "blue", "red"]:
    counts[word] = counts.get(word, 0) + 1
# {"red": 2, "blue": 1}

When to use another structure

Use a dictionary for key-to-value lookup. Use a set when only membership matters, a list when order and indexed access matter, and a deque for efficient operations at both ends. Hash tables do not maintain sorted order; sort keys or use an ordered-search structure when that is the requirement.

Common mistakes with Python Dictionary Lab

  • Assuming worst-case constant time: average performance is constant, but collisions and resizing have costs.
  • **Using setdefault to inspect:** it inserts a missing key as a side effect.
  • Checking values for membership repeatedly: use a set if repeated membership checks are needed.
  • Using a mutable key: its hash and equality behavior must remain stable.

Sources and next steps

Run it in Python

A dict is a hash table with the sharp edges filed off. This program times a lookup against a list scan, shows the four idioms worth knowing, and then demonstrates the two rules people trip over: keys must be hashable, and equal keys are the same key.

dictionaries.pyPython 3
Output

How the code works

  1. stock["apple"]Hash the key, go to the slot, compare. No part of that depends on how many keys there are, which is the whole reason dictionaries are everywhere — see hash tables for the machinery.
  2. probe in haystack_listA list has to compare against every element until it finds one, so in is O(n). Swapping a list for a set is the single highest-value optimisation in most beginner Python.
  3. counts.get(w, 0) + 1The default avoids a KeyError on the first sight of a word without needing an if. defaultdict and Counter are the same idea, pre-packaged.
  4. {[1, 2]: "x"}Keys must be hashable, which in practice means immutable. If a key could change after insertion, its hash would no longer point at the slot it lives in and it would become unreachable.
  5. {1: ..., 1.0: ..., True: ...}One entry, not three. 1 == 1.0 == True and they hash identically, so each assignment overwrites the previous value while keeping the first key object.

Change one thing

  • Time -1 in haystack_list alone. The miss is the worst case: the entire list, every time.
  • Insert keys in a scrambled order and print the dict. Since Python 3.7 insertion order is preserved — a guarantee, not an accident.
  • Use a tuple (row, col) as a key to build a sparse grid. That is how you store a large mostly-empty matrix without allocating it.

Where this runs

Real CPython, compiled to WebAssembly and running on your own machine — nothing is uploaded. The first run takes a few seconds while the interpreter downloads; after that it is immediate. Need more room, or want to paste your own attempt? Use the Python compiler.

Predict, then reveal

About to run: switch Method to .items(). Before it does — what happens to the readout?

Committing to an answer first is the point — the reveal runs the experiment on the visualisation above and reads the real value back, so nothing here is scripted.

Check yourself

0 of 3

Answer without scrolling back up.

  1. Why must dictionary keys be hashable?

  2. {1: 'a', 1.0: 'b', True: 'c'} produces a dict with how many entries?

  3. Replacing 'x in a_big_list' with 'x in a_big_set' changes the cost from:

Cheat sheet

Python Dictionary Lab

Insert, look up and delete key-value pairs in a Python dictionary, and see how hashing makes each operation instant.

ALGORITHMS · vizlearn.in/dsa/dictionaries_in_python.html

Further reading

About the author

Ashish Jangra builds and maintains VizLearn. Every module here is written and the visualisation behind it hand-built, so the numbers in a readout come from the same code that draws the picture. Corrections are genuinely welcome and get priority over everything else — if a page states something wrong, or an animation misrepresents what the algorithm does, get in touch.