Dicts are the most important data structure in Python — objects, JSON and kwargs are all dicts underneath.
A dict maps keys to values: ages = {"ana": 31, "ben": 27}. Lookup by key, ages["ana"], is O(1) on average because dicts are hash tables. Keys must be hashable — immutable built-ins like str, int and tuples of those; lists and dicts can't be keys. Since Python 3.7 dicts preserve insertion order.
Reading a missing key with d[key] raises KeyError. Choose the right tool:
d.get(key)returnsNone(ord.get(key, default)) if absentkey in dtests for a key (not a value)d.setdefault(key, []).append(x)inserts a default the first time
Writing is plain assignment, d[key] = value, which inserts or overwrites. del d[key] and d.pop(key, default) remove. d.update(other) merges in another mapping, and d1 | d2 (3.9+) returns a merged new dict, with the right side winning on conflicts.
Iterating a dict yields its keys. Use the view methods for more:
for k, v in d.items():— both, the most commond.keys(),d.values()— live views that reflect later changes
Counting and grouping are bread-and-butter dict jobs: counts[w] = counts.get(w, 0) + 1. (The collections module's Counter and defaultdict make these even shorter; you'll meet them later.)
Don't add or delete keys while iterating over a dict — Python raises RuntimeError. Iterate over list(d) if you need to.
Example
ages = {"ana": 31, "ben": 27}
ages["cy"] = 40 # insert
ages["ana"] += 1 # update
print(ages) # {'ana': 32, 'ben': 27, 'cy': 40}
print(ages.get("dan")) # None
print(ages.get("dan", 0)) # 0
print("ben" in ages) # True
for name, age in ages.items():
print(f"{name}: {age}")
counts = {}
for word in "the cat and the hat".split():
counts[word] = counts.get(word, 0) + 1
print(counts) # {'the': 2, 'cat': 1, 'and': 1, 'hat': 1}
defaults = {"theme": "light", "size": 12}
print(defaults | {"size": 14}) # {'theme': 'light', 'size': 14}Remember
- Keys must be hashable; lookup is O(1) on average
- Use
.get()orinwhen a key may be missing - Iterate with
.items(); dicts keep insertion order
Watch out for
- Using
d[key]on keys that might not exist and gettingKeyError.