Lists access data by position; dictionaries access data by name. Every ML project config—learning rate, batch size, model name—arrives as JSON-like key-value pairs. Python dict is the native structure for those configs, API responses, and metric dictionaries returned from evaluate().
If you have parsed a Hugging Face or OpenAI API response, you have already used dictionary thinking. This lecture makes it explicit and rigorous.
Learning Objectives
By the end of this lesson, students should be able to:
- Create dictionaries with literals and
dict(). - Access, add, update, and delete key-value pairs.
- Iterate keys, values, and items with safe
.get()access. - Model training configs and evaluation metrics as dictionaries.
- Relate Python dicts to JSON serialization for APIs and experiment tracking.
- Nest dictionaries for hierarchical configs (model, data, optimizer sections).
Key-Value Pairs
A dictionary (dict) maps immutable keys to arbitrary values. Keys are unique; lookup by key is average O(1). Dictionaries mirror JSON objects: {"learning_rate": 0.001, "epochs": 50}.
JSON-Like Configs for AI Pipelines
| Config Section | Example Keys | Purpose |
|---|---|---|
| model | architecture, num_layers, hidden_dim |
Define network structure |
| data | train_path, val_path, num_workers |
Point to datasets and loaders |
| optimizer | lr, betas, weight_decay |
Control parameter updates |
| logging | project, run_name, log_every_n |
Experiment tracking metadata |
List
- Ordered by index
features[0]- Duplicate values allowed
- Best for sequences
Dictionary
- Access by unique key
config["lr"]- Keys must be unique
- Best for configs and records
Safe Access and Iteration
Dictionaries and JSON
JSON (JavaScript Object Notation) is the interchange format for REST APIs, config files, and experiment logs. Python json module converts dicts to JSON strings and back.
JSON is a text format for structured data using objects (key-value maps) and arrays (ordered lists). Python dictionaries map directly to JSON objects when keys are strings and values are JSON-serializable types.
Common Misconceptions
Why people believe it: Older tutorials said dicts were unordered.
Reality: Python 3.7+ guarantees insertion order. Rely on keys for meaning, not position.
Why people believe it: Values can be any type.
Reality: Keys must be hashable—lists and dicts cannot be keys. Use tuples or strings instead.
Why people believe it: They look the same in printouts.
Reality: JSON has no tuples, sets, or None (uses null). Datetime objects and NumPy types need custom serialization.
Quick Knowledge Check
- Short Answer: Syntax to access
lrfromconfig? Answer: config["lr"] or config.get("lr"). - True/False: Dict keys must be unique. Answer: True.
- Multiple Choice: Safest access when key may be missing: (a) [], (b) .get(), (c) pop(), (d) del. Answer: (b).
- Short Answer: What does
metrics.items()yield? Answer: (key, value) pairs. - True/False: A list can be a dictionary key. Answer: False — not hashable.
- Short Answer: Which module converts dict to JSON string? Answer: json (json.dumps).
- Multiple Choice: Best structure for experiment hyperparameters: (a) set, (b) dict, (c) int, (d) bool. Answer: (b).
- True/False: Nested dicts model hierarchical YAML/JSON configs. Answer: True.
- Short Answer: How to add a new key
seedwith value 42? Answer: config["seed"] = 42. - Multiple Choice: JSON
nullmaps to Python: (a) 0, (b) False, (c) None, (d) "". Answer: (c).
Key Takeaways
- Dictionaries map unique keys to values—ideal for configs, metrics, and API payloads.
- Nested dicts represent structured experiment configs (model, data, training sections).
- Use
.get(key, default)for safe access to optional settings. - JSON serializes dicts for files and REST APIs; types are not a perfect superset.
- Keys must be hashable; lists cannot be keys, tuples can.
- Next: Tuple for immutable ordered records.
Hands-on idea: Students write a nested training config dict, load it in a script, and print hyperparameters with a for loop over .items().
API exercise: Parse a sample JSON API response with json.loads and extract nested fields.
Discussion prompt: When should config live in a dict vs a YAML file on disk?