Skip to main content
Albero Academy

Dictionaries

Key–value mappings — Python's most important data structure after the list.

Data Structures12 min

A dictionary maps keys to values, giving instant lookup by key. It's Python's most important structure after the list — you'll use it to model records, count things, cache results, hold configuration, and represent JSON. Under the hood it's a hash table, so lookups are O(1).

Creating & accessing

dict basics
student = {"name": "Aanya", "package": 7.5}
student["name"] # 'Aanya' look up by key
student["email"] = "a@x" # add or update a key
del student["email"] # remove a key
"name" in student # True — key membership
len(student) # number of keys

Safe lookups with .get()

get and setdefault
student.get("phone") # None if missing (no crash)
student.get("phone", "—") # "—" as a fallback
# Count occurrences — get with a default of 0
counts = {}
for word in words:
counts[word] = counts.get(word, 0) + 1

Iterating

looping over a dict
for key in student: # keys by default
print(key)
for value in student.values(): # values
print(value)
for key, value in student.items(): # both — the common one
print(f"{key}: {value}")

What can be a key?

Keys must be immutable (hashable): strings, numbers and tuples work; lists and dicts cannot be keys. Values can be anything — including lists and other dicts, which is how you nest data.

Key takeaways

  1. 01Dictionaries map unique keys to values with O(1) lookup (a hash table).
  2. 02Add/update with d[key] = value; delete with del; test with key in d.
  3. 03Read safely with .get(key, default) to avoid KeyError.
  4. 04Iterate with .items() for key+value (or .keys()/.values()).
  5. 05Keys must be immutable (str, int, tuple); values can be anything.

Finished this chapter?

Mark it complete to track your progress through Python.