Quick Reference: Dictionaries & Tuples
Module 8 Cheat Sheet
Creating Dictionaries
| Syntax | Example |
|---|---|
| Empty dictionary | {} or dict() |
| With values | {"name": "Alice", "age": 25} |
| From keyword args | dict(name="Alice", age=25) |
| From list of tuples | dict([("a", 1), ("b", 2)]) |
Dictionary Operations
| Operation | Syntax | Notes |
|---|---|---|
| Access value | d["key"] | Raises KeyError if missing |
| Safe access | d.get("key", default) | Returns default if missing |
| Add / update | d["key"] = value | Adds if new, updates if exists |
| Delete | del d["key"] | Raises KeyError if missing |
| Check membership | "key" in d | Returns True / False |
| Length | len(d) | Number of key-value pairs |
Dictionary Methods
| Method | Returns | Description |
|---|---|---|
d.keys() | View of keys | All keys in the dictionary |
d.values() | View of values | All values in the dictionary |
d.items() | View of tuples | All (key, value) pairs |
d.get(key, default) | Value or default | Safe access without KeyError |
d.pop(key) | Removed value | Removes key and returns value |
d.update(other) | None | Merges other dict into d |
d.clear() | None | Removes all entries |
d.copy() | New dict | Shallow copy |
d.setdefault(key, val) | Value | Returns value; inserts if missing |
Looping Over Dictionaries
| Pattern | Code |
|---|---|
| Keys | for key in d: |
| Values | for val in d.values(): |
| Key-Value pairs | for key, val in d.items(): |
Tuples
| Operation | Syntax |
|---|---|
| Create tuple | (1, 2, 3) or 1, 2, 3 |
| Single-element tuple | (42,) — trailing comma required |
| Empty tuple | () or tuple() |
| Access element | t[0], t[-1] |
| Slice | t[1:3] |
| Unpack | x, y, z = (1, 2, 3) |
| Swap variables | a, b = b, a |
| Count occurrences | t.count(value) |
| Find index | t.index(value) |
| Length | len(t) |
Choosing a Data Structure
| Use Case | Best Choice |
|---|---|
| Ordered, changeable collection | List |
| Fixed, unchangeable sequence | Tuple |
| Look up by meaningful key/label | Dictionary |
| Data as dictionary key | Tuple (immutable required) |
| Position has meaning (x, y) | Tuple |
| Counting / mapping | Dictionary |