Learn Without Walls
← Back to Module 8

Quick Reference: Dictionaries & Tuples

Module 8 Cheat Sheet

Creating Dictionaries

SyntaxExample
Empty dictionary{} or dict()
With values{"name": "Alice", "age": 25}
From keyword argsdict(name="Alice", age=25)
From list of tuplesdict([("a", 1), ("b", 2)])

Dictionary Operations

OperationSyntaxNotes
Access valued["key"]Raises KeyError if missing
Safe accessd.get("key", default)Returns default if missing
Add / updated["key"] = valueAdds if new, updates if exists
Deletedel d["key"]Raises KeyError if missing
Check membership"key" in dReturns True / False
Lengthlen(d)Number of key-value pairs

Dictionary Methods

MethodReturnsDescription
d.keys()View of keysAll keys in the dictionary
d.values()View of valuesAll values in the dictionary
d.items()View of tuplesAll (key, value) pairs
d.get(key, default)Value or defaultSafe access without KeyError
d.pop(key)Removed valueRemoves key and returns value
d.update(other)NoneMerges other dict into d
d.clear()NoneRemoves all entries
d.copy()New dictShallow copy
d.setdefault(key, val)ValueReturns value; inserts if missing

Looping Over Dictionaries

PatternCode
Keysfor key in d:
Valuesfor val in d.values():
Key-Value pairsfor key, val in d.items():

Tuples

OperationSyntax
Create tuple(1, 2, 3) or 1, 2, 3
Single-element tuple(42,) — trailing comma required
Empty tuple() or tuple()
Access elementt[0], t[-1]
Slicet[1:3]
Unpackx, y, z = (1, 2, 3)
Swap variablesa, b = b, a
Count occurrencest.count(value)
Find indext.index(value)
Lengthlen(t)

Choosing a Data Structure

Use CaseBest Choice
Ordered, changeable collectionList
Fixed, unchangeable sequenceTuple
Look up by meaningful key/labelDictionary
Data as dictionary keyTuple (immutable required)
Position has meaning (x, y)Tuple
Counting / mappingDictionary
Back to Module 8