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
student = {"name": "Aanya", "package": 7.5}student["name"] # 'Aanya' look up by keystudent["email"] = "a@x" # add or update a keydel student["email"] # remove a key"name" in student # True — key membershiplen(student) # number of keys
Safe lookups with .get()
student.get("phone") # None if missing (no crash)student.get("phone", "—") # "—" as a fallback# Count occurrences — get with a default of 0counts = {}for word in words:counts[word] = counts.get(word, 0) + 1
Iterating
for key in student: # keys by defaultprint(key)for value in student.values(): # valuesprint(value)for key, value in student.items(): # both — the common oneprint(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
- 01Dictionaries map unique keys to values with O(1) lookup (a hash table).
- 02Add/update with d[key] = value; delete with del; test with key in d.
- 03Read safely with .get(key, default) to avoid KeyError.
- 04Iterate with .items() for key+value (or .keys()/.values()).
- 05Keys must be immutable (str, int, tuple); values can be anything.
