← Master Index
Vol. 03 Module 3.1 Lecture

Dictionary

Python Basics

How This Lesson Fits the Module

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

Definition — Dictionary

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}.

# Training hyperparameter config config = { "model_name": "resnet-18", "learning_rate": 1e-3, "batch_size": 32, "num_epochs": 50, "use_augmentation": True, } print(config["learning_rate"]) # 0.001 config["weight_decay"] = 1e-4 # add new key config["batch_size"] = 64 # update existing

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
experiment_config = { "model": { "name": "transformer-small", "num_heads": 8, "hidden_dim": 512, }, "training": { "learning_rate": 3e-4, "batch_size": 16, "max_epochs": 100, }, "data": { "train_file": "data/train.jsonl", "val_file": "data/val.jsonl", }, } lr = experiment_config["training"]["learning_rate"] print(f"Training with lr={lr}")

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

metrics = {"accuracy": 0.94, "f1": 0.91, "loss": 0.23} # Safe access with default — missing keys won't crash recall = metrics.get("recall", 0.0) # Iterate for logging for name, value in metrics.items(): print(f"{name}: {value:.4f}") # Keys must be hashable — strings, numbers, tuples of immutables valid_key = ("split", "train") # tuple key for multi-index lookup

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.

Definition — JSON

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.

import json run_summary = { "run_id": "exp-042", "metrics": {"val_accuracy": 0.96, "val_loss": 0.18}, "hyperparameters": {"lr": 1e-3, "batch_size": 32}, } # Serialize to JSON string for API or file json_str = json.dumps(run_summary, indent=2) # Parse JSON from API response api_response = json.loads('{"status": "ok", "model": "gpt-4"}') model = api_response["model"]
What’s Next in This ModuleThe next lecture, Tuple, covers immutable sequences—useful for fixed schemas, coordinates, and dictionary keys.

Common Misconceptions

Misconception 1: “Dictionaries preserve insertion order only in recent Python.”

Why people believe it: Older tutorials said dicts were unordered.

Reality: Python 3.7+ guarantees insertion order. Rely on keys for meaning, not position.

Misconception 2: “Any object can be a dict key.”

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.

Misconception 3: “JSON and Python dict are identical.”

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

  1. Short Answer: Syntax to access lr from config? Answer: config["lr"] or config.get("lr").
  2. True/False: Dict keys must be unique. Answer: True.
  3. Multiple Choice: Safest access when key may be missing: (a) [], (b) .get(), (c) pop(), (d) del. Answer: (b).
  4. Short Answer: What does metrics.items() yield? Answer: (key, value) pairs.
  5. True/False: A list can be a dictionary key. Answer: False — not hashable.
  6. Short Answer: Which module converts dict to JSON string? Answer: json (json.dumps).
  7. Multiple Choice: Best structure for experiment hyperparameters: (a) set, (b) dict, (c) int, (d) bool. Answer: (b).
  8. True/False: Nested dicts model hierarchical YAML/JSON configs. Answer: True.
  9. Short Answer: How to add a new key seed with value 42? Answer: config["seed"] = 42.
  10. Multiple Choice: JSON null maps 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.
Trainer’s Guide

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?

What’s Next Continue to Tuple for fixed-length, immutable sequences.