Python 101Free
DATA STRUCTURES

Dictionaries

Key value mappings, the workhorse of Python.

SECTION 01

Lookup as a hash map

Any time you need to look something up by name in constant time, a dict is the answer. When you write d["name"], Python hashes the key, finds the bucket that hash points to, and returns the value stored there. The hashing means lookup is amortized O(1), regardless of how many keys are in the dict.

Keys must be hashable, which in practice means immutable. Strings, numbers, and tuples work as keys. Lists and other dicts do not, because their hash would change if their contents changed.

Dict is the data structure you reach for whenever you need to look something up by name. Counting word frequencies, caching results, configuring options, structuring records returned from an API: all dicts.

python
user = {"name": "Ada", "score": 92}
user["name"]            # 'Ada'

# user[[1, 2]] = "x"    # TypeError: list is unhashable
2 more sections

Create a free account to access all sections and animations.

Create free accountAlready have an account? Sign in