Dicts are ordered since Python 3.7. Key hashing rules. The difference between [] and .get(). Merging with |. Never mutate while iterating.
d = {"a": 1, "b": 2}
print(d["a"])
print(d.get("b"))
print(d.get("c"))
print(d.get("c", 99))
d["c"] would raise KeyError. d.get("c") returns None (safe default). d.get("c", 99) returns 99 (custom default). Use .get() when the key might not exist to avoid KeyError.d = {"a": 1}
d["b"]
[] raises KeyError. This is different from .get() which returns None. Common pattern to avoid: if "b" in d: print(d["b"]) — but better to just use d.get("b").d = {"a": 1}
d.setdefault("a", 99)
d.setdefault("b", 99)
print(d)
.setdefault(key, default) sets the key to the default only if the key does NOT already exist. "a" already exists with value 1 — it stays 1, the 99 is ignored. "b" doesn't exist — it's set to 99. It also returns the current value for the key.from collections import defaultdict d = defaultdict(list) d["a"].append(1) d["a"].append(2) d["b"].append(3) print(dict(d))
defaultdict(list) automatically creates an empty list when you access a missing key. No need to check if the key exists first. Extremely useful for grouping items. defaultdict(int) auto-creates 0, defaultdict(set) auto-creates empty set, etc.d = {"x": 1, "y": 2, "z": 3}
print(list(d.keys()))
print(list(d.values()))
print(list(d.items()))
.keys(), .values(), .items() return view objects — they reflect changes to the dict in real time. Wrap in list() to get a snapshot. .items() returns key-value pairs as tuples, perfect for for k, v in d.items().d = {"a": 1, "b": 2}
keys = d.keys()
d["c"] = 3
print(len(keys))
"c" to the dict is immediately visible through the keys view. This is different from calling list(d.keys()) which creates a static snapshot at that moment.a = {"x": 1, "y": 2}
b = {"y": 99, "z": 3}
c = a | b # Python 3.9+
a |= b # in-place merge
print(c)
print(a)
| operator (Python 3.9+) merges two dicts. When keys conflict, the right-hand dict wins. a | b creates a new dict. a |= b updates a in place. Before 3.9: {**a, **b} was the idiom (right-side wins on conflicts too).a = {"x": 1}
b = {"x": 2, "y": 3}
c = {**a, **b}
d = {**b, **a}
print(c["x"])
print(d["x"])
{**a, **b} — later entries overwrite earlier ones. b comes last, so b["x"]=2 wins. {**b, **a} — a comes last, so a["x"]=1 wins. The order of spread matters for conflict resolution.d = {}
d["c"] = 3
d["a"] = 1
d["b"] = 2
print(list(d.keys()))
d = {}
d[True] = "bool"
d[1] = "int"
d[1.0] = "float"
print(d)
print(len(d))
True == 1 == 1.0 and they all have the same hash. Dict keys are unique by value — so True, 1, and 1.0 are all considered the SAME key. The first one (True) stays as the key, but the value is overwritten each time. One key, three assignments, final value is "float".d = {[1, 2]: "value"}
TypeError: unhashable type: 'list'. Use a tuple instead: {(1, 2): "value"}. Hashable types: int, float, str, bool, frozenset, tuple (of hashables). Unhashable: list, dict, set.d = {"a": 1, "b": 2, "c": 3}
for k in d:
if k == "b":
del d[k]
RuntimeError: dictionary changed size during iteration. Safe fix: iterate over a copy of keys: for k in list(d): or build a new dict: d = {k: v for k, v in d.items() if k != "b"}.squares = {x: x**2 for x in range(5)}
print(squares)
evens = {k: v for k, v in squares.items() if v % 2 == 0}
print(evens)
{key_expr: val_expr for item in iterable if condition}. The first creates x → x² for 0-4. The second filters to only even values (0, 4, 16 are even). Very Pythonic way to transform and filter dicts.d = {"a": 1, "b": 2}
inv = {v: k for k, v in d.items()}
print(inv)
d = {"a": 1, "b": 2, "c": 3}
val = d.pop("b")
print(val)
print(d)
print(d.pop("z", "not found"))
.pop(key) removes and returns the value. .pop(key, default) returns the default if key not found (no error). Without a default, .pop() on a missing key raises KeyError.d = {"a": 1}
d.update({"b": 2, "a": 99})
print(d)
.update(other_dict) merges in-place — existing keys are overwritten with the new values. "a" was 1, updated to 99. "b" is new, added with value 2. The order is: existing keys maintain their relative order, new keys are appended at the end.d = {"a": [1, 2]}
e = d.copy()
e["a"].append(3)
print(d["a"])
dict.copy() is a shallow copy — the dict itself is new, but the values are shared references. e["a"] and d["a"] point to the same list. Mutating through either affects the shared object. Use copy.deepcopy(d) to get fully independent copies.d = {"a": 1, "b": 2}
print("a" in d)
print(1 in d)
print(1 in d.values())
in on a dict checks keys, not values. "a" in d → True (key exists). 1 in d → False (1 is not a key). 1 in d.values() → True (1 is a value). Key lookup is O(1) via hash. Value lookup is O(n) — it has to scan all values.