dict maps hashable keys to values with average O(1) lookup, insert and delete — the workhorse of Python.
Create, read, update
ages = {"asha": 25, "ravi": 30}
ages["kiran"] = 28 # insert / update
print(ages["asha"]) # 25
print(ages.get("zoe"), ages.get("zoe", 0)) # None 0
print("ravi" in ages, len(ages)) # True 3
del ages["ravi"]
print(ages.pop("kiran"), ages) # 28 {'asha': 25}Iterating
scores = {"math": 90, "cs": 95}
for subject, score in scores.items():
print(subject, score, end="; ") # math 90; cs 95;
print()
print(list(scores), list(scores.values())) # ['math', 'cs'] [90, 95]Useful methods
| Method | Does |
|---|---|
d.get(k, default) | Value or default — never raises |
d.setdefault(k, v) | Insert v if k is missing, then return d[k] |
d.update(other) / d | other | Merge (the right-hand side wins); | returns a new dict (3.9+) |
d.pop(k, default) | Remove and return |
d.items() / keys() / values() | Live views that reflect later changes |
dict.fromkeys(keys, v) | New dict with every key set to v |
base = {"theme": "light", "font": 14}
user = {"theme": "dark"}
print(base | user) # {'theme': 'dark', 'font': 14}
counts = {}
for ch in "banana":
counts[ch] = counts.get(ch, 0) + 1
print(counts) # {'b': 1, 'a': 3, 'n': 2}
print(max(counts, key=counts.get)) # aWhat can be a key?
Keys must be hashable: their hash never changes during their lifetime. Immutable built-ins (int, str, tuple of hashables, frozenset) are hashable; list, dict and set are not.
grid = {(0, 0): "start", (2, 3): "goal"} # tuples make great coordinate keys
print(grid[(2, 3)]) # goal
try:
{[1, 2]: "x"} # lists are unhashable
except TypeError as e:
print(type(e).__name__) # TypeErrorDictionary patterns
def two_sum(nums, target):
seen = {} # value → index
for i, x in enumerate(nums):
if target - x in seen:
return [seen[target - x], i]
seen[x] = i
return []
print(two_sum([2, 7, 11, 15], 9)) # [0, 1]