Python dictionaries — keys, values, and methods
dict creation, key access, get method, update, delete keys, iterating dict, dict comprehension, nested dicts
Dictionaries
A dictionary stores key-value pairs. Keys must be hashable (strings, ints, tuples). Access is O(1) on average — faster than scanning a list.
user = {
"name": "Alice",
"age": 30,
"active": True
}
print(user["name"]) # Alice
print(user.get("email", "")) # "" — safe default
Modifying a Dict
user["age"] = 31 # update existing
user["email"] = "a@b.com" # add new key
del user["active"] # remove key
user.update({"city": "NY", "age": 32}) # merge
Iterating
for key in user: # keys only
print(key, user[key])
for k, v in user.items(): # key-value pairs
print(f"{k}: {v}")
keys = list(user.keys())
values = list(user.values())
Dict Comprehension
squares = {n: n**2 for n in range(1, 6)}
# {1:1, 2:4, 3:9, 4:16, 5:25}
Use .get(key, default) instead of direct access when a key might be absent — it avoids a KeyError.
Dictionaries are the workhorses of Python programs — configuration, caches, frequency maps, lookup tables, and JSON data all end up as dicts. Since Python 3.7, dictionaries preserve insertion order, so iteration is predictable. The collections.defaultdict removes the need to check for key existence before appending — defaultdict(list) auto-creates an empty list for missing keys. When building lookup tables from large datasets, a dict is almost always the right structure: O(1) average-case access versus O(n) for scanning a list.
