{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "55a0666a",
   "metadata": {},
   "source": [
    "# Dictionary Patterns"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "1f0c8403",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.401942Z",
     "iopub.status.busy": "2026-10-13T02:11:14.401863Z",
     "iopub.status.idle": "2026-10-13T02:11:14.784215Z",
     "shell.execute_reply": "2026-10-13T02:11:14.783731Z"
    },
    "tags": [
     "hide-input",
     "thebe-init"
    ]
   },
   "outputs": [],
   "source": [
    "import sys\n",
    "from pathlib import Path\n",
    "\n",
    "# Find project root by looking for _config.yml\n",
    "current = Path.cwd()\n",
    "for parent in [current, *current.parents]:\n",
    "    if (parent / '_config.yml').exists():\n",
    "        project_root = parent\n",
    "        break\n",
    "else:\n",
    "    project_root = Path.cwd().parent.parent\n",
    "\n",
    "# Add project root to path\n",
    "sys.path.insert(0, str(project_root))\n",
    "\n",
    "# Import shared teaching helpers and cell magics\n",
    "from shared import thinkpython, diagram, jupyturtle, structshape\n",
    "from shared.download import download\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "78241c9b",
   "metadata": {},
   "source": [
    "Dictionaries support three recurring tasks: transforming existing data, counting and grouping observations, and modeling records with useful keys. Start by choosing what each key means and what its value should hold.\n",
    "\n",
    "| Task | Key | Value | Pattern |\n",
    "| --- | --- | --- | --- |\n",
    "| Transform prices | Fruit name | Adjusted price | Comprehension |\n",
    "| Count observations | Observed category | Frequency | Counting loop or `Counter` |\n",
    "| Group records | Shared category | List of records | `defaultdict(list)` |\n",
    "| Store a record | Field name | Field value or inner dictionary | Nested dictionary |\n",
    "| Look up by two fields | Tuple of fields | Associated value | Tuple key |\n",
    "\n",
    "The examples first show the loop and the resulting data, then introduce a shorter form. Lookup performance and memoization appear at the end as extensions."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "db3f3cde",
   "metadata": {},
   "source": [
    "```{contents}\n",
    ":local:\n",
    ":depth: 2\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "912bdf5d",
   "metadata": {},
   "source": [
    "## Transforming Dictionary Data\n",
    "\n",
    "### Iterate Through Keys and Values\n",
    "\n",
    "A loop over a dictionary visits its keys in insertion order. Use `values()` when only the values matter and `items()` when you need both. Insertion order is not alphabetical order; use `sorted()` when a report needs a sorted presentation."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-912bdf5d",
   "metadata": {},
   "source": [
    "```{index} dictionary iteration, dict.values()\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "310e1489",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.785662Z",
     "iopub.status.busy": "2026-10-13T02:11:14.785538Z",
     "iopub.status.idle": "2026-10-13T02:11:14.787616Z",
     "shell.execute_reply": "2026-10-13T02:11:14.787291Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'b': 1, 'a': 3, 'n': 2}\n"
     ]
    }
   ],
   "source": [
    "counter = {'b': 1, 'a': 3, 'n': 2}\n",
    "print(counter)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fe263f3d",
   "metadata": {},
   "source": [
    "The following loop prints the keys, which are the letters."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "da4ec7fd",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.788637Z",
     "iopub.status.busy": "2026-10-13T02:11:14.788570Z",
     "iopub.status.idle": "2026-10-13T02:11:14.790065Z",
     "shell.execute_reply": "2026-10-13T02:11:14.789885Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "b\n",
      "a\n",
      "n\n"
     ]
    }
   ],
   "source": [
    "for key in counter:\n",
    "    print(key)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bf1b7824",
   "metadata": {},
   "source": [
    "To print the values, we can use the `values` method."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "859fe1ad",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.790859Z",
     "iopub.status.busy": "2026-10-13T02:11:14.790798Z",
     "iopub.status.idle": "2026-10-13T02:11:14.793769Z",
     "shell.execute_reply": "2026-10-13T02:11:14.793318Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "3\n",
      "2\n"
     ]
    }
   ],
   "source": [
    "for value in counter.values():\n",
    "    print(value)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "721135be",
   "metadata": {},
   "source": [
    "Use `items()` to obtain each `(key, value)` pair directly. Tuple unpacking gives the two parts meaningful names."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "7242ab5b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.794729Z",
     "iopub.status.busy": "2026-10-13T02:11:14.794660Z",
     "iopub.status.idle": "2026-10-13T02:11:14.796128Z",
     "shell.execute_reply": "2026-10-13T02:11:14.795947Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "b 1\n",
      "a 3\n",
      "n 2\n"
     ]
    }
   ],
   "source": [
    "for letter, frequency in counter.items():\n",
    "    print(letter, frequency)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "e533c7d7",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.797099Z",
     "iopub.status.busy": "2026-10-13T02:11:14.797023Z",
     "iopub.status.idle": "2026-10-13T02:11:14.798471Z",
     "shell.execute_reply": "2026-10-13T02:11:14.798282Z"
    },
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Iterating Through a Dictionary\n",
    "# Use this dictionary:\n",
    "# 1. Print only the names (keys).\n",
    "# 2. Print only the scores (values).\n",
    "# 3. Print each name and score together using .items().\n",
    "scores = {\"alice\": 92, \"bob\": 85, \"charlie\": 78}\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "edcc0f5d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.799495Z",
     "iopub.status.busy": "2026-10-13T02:11:14.799432Z",
     "iopub.status.idle": "2026-10-13T02:11:14.801808Z",
     "shell.execute_reply": "2026-10-13T02:11:14.801574Z"
    },
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "alice\n",
      "bob\n",
      "charlie\n",
      "92\n",
      "85\n",
      "78\n",
      "alice 92\n",
      "bob 85\n",
      "charlie 78\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "scores = {\"alice\": 92, \"bob\": 85, \"charlie\": 78}\n",
    "\n",
    "# 1. Keys only\n",
    "for name in scores:\n",
    "    print(name)\n",
    "\n",
    "# 2. Values only\n",
    "for score in scores.values():\n",
    "    print(score)\n",
    "\n",
    "# 3. Key-value pairs\n",
    "for name, score in scores.items():\n",
    "    print(name, score)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0e1352f4",
   "metadata": {},
   "source": [
    "`keys()`, `values()`, and `items()` return **views**: they reflect later changes to the dictionary. A list made from a view is a snapshot. You can update existing values while iterating, but do not add or remove keys from the dictionary being traversed. Build a new dictionary or iterate over a snapshot when changing its entries."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "871af36f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.802786Z",
     "iopub.status.busy": "2026-10-13T02:11:14.802713Z",
     "iopub.status.idle": "2026-10-13T02:11:14.804339Z",
     "shell.execute_reply": "2026-10-13T02:11:14.804181Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "View: ['apple', 'banana', 'cherry']\n",
      "Snapshot: ['apple', 'banana']\n"
     ]
    }
   ],
   "source": [
    "prices = {'apple': 1.20, 'banana': 0.50}\n",
    "keys_view = prices.keys()\n",
    "keys_snapshot = list(prices)\n",
    "prices['cherry'] = 2.00\n",
    "print('View:', list(keys_view))\n",
    "print('Snapshot:', keys_snapshot)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "df773f07",
   "metadata": {},
   "source": [
    "### Build and Filter with a Comprehension\n",
    "\n",
    "A dictionary comprehension builds a new dictionary from an iterable. Each iteration produces a key and a value:\n",
    "\n",
    "```python\n",
    "{key_expr: value_expr for item in iterable if condition}\n",
    "```\n",
    "\n",
    "The `if` clause is optional. Start with a loop when the transformation has several steps; use a comprehension when the key, value, and condition remain easy to read."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ace87464",
   "metadata": {},
   "source": [
    "```{index} dictionary comprehension\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "2f61c53f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.805472Z",
     "iopub.status.busy": "2026-10-13T02:11:14.805393Z",
     "iopub.status.idle": "2026-10-13T02:11:14.807586Z",
     "shell.execute_reply": "2026-10-13T02:11:14.807414Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'apple': 1.08, 'banana': 0.45, 'cherry': 1.8}\n",
      "{'apple': 1.08, 'banana': 0.45, 'cherry': 1.8}\n",
      "{'apple': 1.2, 'cherry': 2.0}\n"
     ]
    }
   ],
   "source": [
    "prices = {'apple': 1.20, 'banana': 0.50, 'cherry': 2.00}\n",
    "discounted = {}\n",
    "for fruit, price in prices.items():\n",
    "    discounted[fruit] = round(price * 0.9, 2)\n",
    "print(discounted)\n",
    "\n",
    "# Same transformation, expressed as a comprehension.\n",
    "discounted = {fruit: round(price * 0.9, 2) for fruit, price in prices.items()}\n",
    "print(discounted)\n",
    "\n",
    "# Keep entries that meet the condition.\n",
    "pricey = {fruit: price for fruit, price in prices.items() if price > 1.00}\n",
    "print(pricey)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "cff2cd5d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.809025Z",
     "iopub.status.busy": "2026-10-13T02:11:14.808926Z",
     "iopub.status.idle": "2026-10-13T02:11:14.810502Z",
     "shell.execute_reply": "2026-10-13T02:11:14.810323Z"
    },
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Dictionary Comprehension\n",
    "# 1. Use a dict comprehension to create a dictionary that maps\n",
    "#    each number 1-5 to its cube (n**3).\n",
    "# 2. Given the prices dict below, use a dict comprehension to keep\n",
    "#    only fruits that cost more than $1.00.\n",
    "prices = {'apple': 1.20, 'banana': 0.50, 'cherry': 2.00, 'grape': 0.80}\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "c768140f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.811294Z",
     "iopub.status.busy": "2026-10-13T02:11:14.811226Z",
     "iopub.status.idle": "2026-10-13T02:11:14.813366Z",
     "shell.execute_reply": "2026-10-13T02:11:14.813146Z"
    },
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Cubes: {1: 1, 2: 8, 3: 27, 4: 64, 5: 125}\n",
      "Pricey: {'apple': 1.2, 'cherry': 2.0}\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "# 1. Cubes\n",
    "cubes = {n: n**3 for n in range(1, 6)}\n",
    "print(\"Cubes:\", cubes)\n",
    "\n",
    "# 2. Expensive fruits\n",
    "prices = {'apple': 1.20, 'banana': 0.50, 'cherry': 2.00, 'grape': 0.80}\n",
    "pricey = {fruit: price for fruit, price in prices.items() if price > 1.00}\n",
    "print(\"Pricey:\", pricey)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "da23616d",
   "metadata": {},
   "source": [
    "## Counting and Grouping Observations\n",
    "\n",
    "### Count with a Dictionary\n",
    "\n",
    "To count observations, use each observed value as a key and its frequency as the value. After each loop iteration, the dictionary holds the counts for everything seen so far. A new key starts at one; an existing key increases by one."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-da23616d",
   "metadata": {},
   "source": [
    "```{index} frequency count, counter pattern\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "d800452b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.814234Z",
     "iopub.status.busy": "2026-10-13T02:11:14.814169Z",
     "iopub.status.idle": "2026-10-13T02:11:14.815487Z",
     "shell.execute_reply": "2026-10-13T02:11:14.815321Z"
    }
   },
   "outputs": [],
   "source": [
    "counter = {}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "21732020",
   "metadata": {},
   "source": [
    "As we loop through the letters in the string, suppose we see the letter `'a'` for the first time.\n",
    "We can add it to the dictionary like this."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "1bac940d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.816667Z",
     "iopub.status.busy": "2026-10-13T02:11:14.816574Z",
     "iopub.status.idle": "2026-10-13T02:11:14.818186Z",
     "shell.execute_reply": "2026-10-13T02:11:14.817840Z"
    }
   },
   "outputs": [],
   "source": [
    "counter['a'] = 1"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fb83e4ab",
   "metadata": {},
   "source": [
    "The value `1` indicates that we have seen the letter once.\n",
    "Later, if we see the same letter again, we can increment the counter like this."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "7a29d3c5",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.819320Z",
     "iopub.status.busy": "2026-10-13T02:11:14.819257Z",
     "iopub.status.idle": "2026-10-13T02:11:14.820558Z",
     "shell.execute_reply": "2026-10-13T02:11:14.820377Z"
    }
   },
   "outputs": [],
   "source": [
    "counter['a'] += 1"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a6cd4999",
   "metadata": {},
   "source": [
    "Now the value associated with `'a'` is `2`, because we've seen the letter twice."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "2ca074c6",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.821257Z",
     "iopub.status.busy": "2026-10-13T02:11:14.821207Z",
     "iopub.status.idle": "2026-10-13T02:11:14.823329Z",
     "shell.execute_reply": "2026-10-13T02:11:14.823166Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'a': 2}"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "counter"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ca68ff9e",
   "metadata": {},
   "source": [
    "The following function uses these features to count the number of times each letter appears in a string."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a91d784b",
   "metadata": {},
   "source": [
    "(value_counts)="
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "c9be0de9",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.824086Z",
     "iopub.status.busy": "2026-10-13T02:11:14.824039Z",
     "iopub.status.idle": "2026-10-13T02:11:14.825357Z",
     "shell.execute_reply": "2026-10-13T02:11:14.825208Z"
    }
   },
   "outputs": [],
   "source": [
    "def value_counts(values):\n",
    "    \"\"\"Count occurrences of hashable values in an iterable.\"\"\"\n",
    "    counts = {}\n",
    "    for value in values:\n",
    "        if value not in counts:\n",
    "            counts[value] = 1\n",
    "        else:\n",
    "            counts[value] += 1\n",
    "    return counts"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cb1c1f64",
   "metadata": {},
   "source": [
    "The loop handles first and repeated occurrences separately. The same function works on a string of letters or a list of categories, because both provide one value per iteration."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "e4dbc1c3",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.826056Z",
     "iopub.status.busy": "2026-10-13T02:11:14.826009Z",
     "iopub.status.idle": "2026-10-13T02:11:14.827552Z",
     "shell.execute_reply": "2026-10-13T02:11:14.827396Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'b': 1, 'r': 2, 'o': 2, 'n': 1, 't': 1, 's': 2, 'a': 1, 'u': 2}"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "counter = value_counts('brontosaurus')\n",
    "counter"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "75ae9b41",
   "metadata": {},
   "source": [
    "The items in `counter` show that the letter `'b'` appears once, `'r'` appears twice, and so on."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "871bead9",
   "metadata": {},
   "source": [
    "The expression `counts.get(value, 0) + 1` combines the two cases. `get()` returns the existing count or zero without inserting anything; the assignment stores the incremented count."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "85a53046",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.828344Z",
     "iopub.status.busy": "2026-10-13T02:11:14.828291Z",
     "iopub.status.idle": "2026-10-13T02:11:14.829724Z",
     "shell.execute_reply": "2026-10-13T02:11:14.829486Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'sales': 2, 'ops': 3, 'data': 1}\n"
     ]
    }
   ],
   "source": [
    "departments = ['sales', 'ops', 'sales', 'data', 'ops', 'ops']\n",
    "counts = {}\n",
    "for department in departments:\n",
    "    counts[department] = counts.get(department, 0) + 1\n",
    "print(counts)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "b52d3ba5",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.830441Z",
     "iopub.status.busy": "2026-10-13T02:11:14.830391Z",
     "iopub.status.idle": "2026-10-13T02:11:14.831981Z",
     "shell.execute_reply": "2026-10-13T02:11:14.831513Z"
    },
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Counting with a Dictionary\n",
    "# 1. Write a counting loop for the observations below.\n",
    "# 2. Use .get(fruit, 0) + 1 to handle both first and repeated occurrences.\n",
    "# 3. Print the counts and check that their sum equals the number of observations.\n",
    "fruits = ['apple', 'banana', 'apple', 'cherry', 'banana', 'apple']\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "962130bf",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.834220Z",
     "iopub.status.busy": "2026-10-13T02:11:14.834030Z",
     "iopub.status.idle": "2026-10-13T02:11:14.836301Z",
     "shell.execute_reply": "2026-10-13T02:11:14.835880Z"
    },
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'apple': 3, 'banana': 2, 'cherry': 1}\n",
      "True\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "fruits = ['apple', 'banana', 'apple', 'cherry', 'banana', 'apple']\n",
    "counts = {}\n",
    "for fruit in fruits:\n",
    "    counts[fruit] = counts.get(fruit, 0) + 1\n",
    "print(counts)\n",
    "print(sum(counts.values()) == len(fruits))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "14468ec6",
   "metadata": {},
   "source": [
    "### Count with Counter\n",
    "\n",
    "`Counter` from `collections` implements the counting pattern for hashable values. Use the manual loop to understand how counts are accumulated, then use `Counter` when the task is simply counting. Its `most_common(n)` method returns the leading `(value, count)` pairs."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1a669ec3",
   "metadata": {},
   "source": [
    "```{index} Counter\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "85452c7f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.837427Z",
     "iopub.status.busy": "2026-10-13T02:11:14.837338Z",
     "iopub.status.idle": "2026-10-13T02:11:14.838863Z",
     "shell.execute_reply": "2026-10-13T02:11:14.838685Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Counter({'r': 2, 'o': 2, 's': 2, 'u': 2, 'b': 1, 'n': 1, 't': 1, 'a': 1})\n",
      "[('r', 2), ('o', 2), ('s', 2)]\n"
     ]
    }
   ],
   "source": [
    "from collections import Counter\n",
    "\n",
    "# Counter accepts a string, list, or any iterable\n",
    "counts = Counter('brontosaurus')\n",
    "print(counts)\n",
    "\n",
    "# most_common(n) returns the n highest-frequency items as (element, count) pairs\n",
    "print(counts.most_common(3))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "31251391",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.839626Z",
     "iopub.status.busy": "2026-10-13T02:11:14.839557Z",
     "iopub.status.idle": "2026-10-13T02:11:14.841461Z",
     "shell.execute_reply": "2026-10-13T02:11:14.841283Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a:     Counter({'a': 2, 'b': 1})\n",
      "b:     Counter({'a': 1, 'b': 1, 'c': 1})\n",
      "a + b: Counter({'a': 3, 'b': 2, 'c': 1})\n",
      "a - b: Counter({'a': 1})\n",
      "a & b: Counter({'a': 1, 'b': 1})\n",
      "a | b: Counter({'a': 2, 'b': 1, 'c': 1})\n"
     ]
    }
   ],
   "source": [
    "from collections import Counter\n",
    "\n",
    "a = Counter('aab')\n",
    "b = Counter('abc')\n",
    "print('a:    ', a)\n",
    "print('b:    ', b)\n",
    "print('a + b:', a + b)   # add counts\n",
    "print('a - b:', a - b)   # subtract, drop non-positive\n",
    "print('a & b:', a & b)   # intersection: min of each count\n",
    "print('a | b:', a | b)   # union: max of each count"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "e7d17d04",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.842296Z",
     "iopub.status.busy": "2026-10-13T02:11:14.842238Z",
     "iopub.status.idle": "2026-10-13T02:11:14.843541Z",
     "shell.execute_reply": "2026-10-13T02:11:14.843365Z"
    },
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Counter\n",
    "# Given the list of words below:\n",
    "# 1. Use Counter to count word frequencies.\n",
    "# 2. Print the two most common words with their counts (tab-separated).\n",
    "# 3. Create a second Counter for ['banana', 'cherry', 'date'] and print\n",
    "#    the combined counts using +.\n",
    "words = ['apple', 'banana', 'apple', 'cherry', 'banana', 'apple']\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "b476e9ce",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.844595Z",
     "iopub.status.busy": "2026-10-13T02:11:14.844539Z",
     "iopub.status.idle": "2026-10-13T02:11:14.846587Z",
     "shell.execute_reply": "2026-10-13T02:11:14.846094Z"
    },
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Counter({'apple': 3, 'banana': 2, 'cherry': 1})\n",
      "3\tapple\n",
      "2\tbanana\n",
      "Counter({'apple': 3, 'banana': 3, 'cherry': 2, 'date': 1})\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "from collections import Counter\n",
    "\n",
    "words = ['apple', 'banana', 'apple', 'cherry', 'banana', 'apple']\n",
    "\n",
    "# 1. Count\n",
    "c1 = Counter(words)\n",
    "print(c1)\n",
    "\n",
    "# 2. Top 2\n",
    "for word, count in c1.most_common(2):\n",
    "    print(count, word, sep='\\t')\n",
    "\n",
    "# 3. Combined\n",
    "c2 = Counter(['banana', 'cherry', 'date'])\n",
    "print(c1 + c2)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2620fb55",
   "metadata": {},
   "source": [
    "### Group with defaultdict\n",
    "\n",
    "Grouping collects several values under one key. For example, a student's name can map to a list of course codes. With a regular dictionary, create the list before appending. `setdefault(key, [])` returns the existing list or inserts and returns a new one.\n",
    "\n",
    "`defaultdict(list)` automates that step when you access a missing key with square brackets. The **factory function**, `list`, creates a separate empty list for each new key. Use `defaultdict(int)` for numeric accumulation because `int()` produces zero."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7119f914",
   "metadata": {},
   "source": [
    "```{index} defaultdict\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "b6d3ee01",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.847971Z",
     "iopub.status.busy": "2026-10-13T02:11:14.847892Z",
     "iopub.status.idle": "2026-10-13T02:11:14.850008Z",
     "shell.execute_reply": "2026-10-13T02:11:14.849694Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'Ana': ['CS101', 'DS201'], 'Ben': ['CS101']}\n"
     ]
    }
   ],
   "source": [
    "records = [('Ana', 'CS101'), ('Ben', 'CS101'), ('Ana', 'DS201')]\n",
    "courses = {}\n",
    "for name, course in records:\n",
    "    courses.setdefault(name, []).append(course)\n",
    "print(courses)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "ccb16fad",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.850977Z",
     "iopub.status.busy": "2026-10-13T02:11:14.850911Z",
     "iopub.status.idle": "2026-10-13T02:11:14.852627Z",
     "shell.execute_reply": "2026-10-13T02:11:14.852304Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'the': 3, 'cat': 2, 'sat': 2, 'on': 1, 'mat': 1, 'and': 1}\n"
     ]
    }
   ],
   "source": [
    "from collections import defaultdict\n",
    "\n",
    "# int factory: missing keys default to 0 — no KeyError, no if-check needed\n",
    "word_count = defaultdict(int)\n",
    "for word in 'the cat sat on the mat and the cat sat'.split():\n",
    "    word_count[word] += 1\n",
    "\n",
    "print(dict(word_count))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "950724f1",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.853595Z",
     "iopub.status.busy": "2026-10-13T02:11:14.853530Z",
     "iopub.status.idle": "2026-10-13T02:11:14.855255Z",
     "shell.execute_reply": "2026-10-13T02:11:14.855080Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "alice ['CS101', 'DS201']\n",
      "bob ['CS101', 'DS201']\n",
      "charlie ['CS101']\n"
     ]
    }
   ],
   "source": [
    "from collections import defaultdict\n",
    "\n",
    "# list factory: group records by a key — no \"if key not in d\" needed\n",
    "records = [\n",
    "    ('alice', 'CS101'), ('bob', 'CS101'),\n",
    "    ('alice', 'DS201'), ('charlie', 'CS101'),\n",
    "    ('bob',   'DS201'),\n",
    "]\n",
    "\n",
    "courses = defaultdict(list)\n",
    "for name, course in records:\n",
    "    courses[name].append(course)   # first access auto-creates an empty list\n",
    "\n",
    "for name, taken in courses.items():\n",
    "    print(name, taken)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "a29b13c3",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.856308Z",
     "iopub.status.busy": "2026-10-13T02:11:14.856242Z",
     "iopub.status.idle": "2026-10-13T02:11:14.857725Z",
     "shell.execute_reply": "2026-10-13T02:11:14.857566Z"
    },
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: defaultdict\n",
    "# 1. Use defaultdict(list) to group sales amounts by region.\n",
    "# 2. Use defaultdict(int) to compute total sales per region.\n",
    "# 3. Print both results.\n",
    "sales = [\n",
    "    ('north', 120), ('south', 85), ('north', 200),\n",
    "    ('east', 60),   ('south', 150), ('east', 90),\n",
    "]\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "5c3b9480",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.858485Z",
     "iopub.status.busy": "2026-10-13T02:11:14.858419Z",
     "iopub.status.idle": "2026-10-13T02:11:14.860165Z",
     "shell.execute_reply": "2026-10-13T02:11:14.860006Z"
    },
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'north': [120, 200], 'south': [85, 150], 'east': [60, 90]}\n",
      "{'north': 320, 'south': 235, 'east': 150}\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "from collections import defaultdict\n",
    "\n",
    "sales = [\n",
    "    ('north', 120), ('south', 85), ('north', 200),\n",
    "    ('east', 60),   ('south', 150), ('east', 90),\n",
    "]\n",
    "\n",
    "# 1. Group amounts by region\n",
    "by_region = defaultdict(list)\n",
    "for region, amount in sales:\n",
    "    by_region[region].append(amount)\n",
    "print(dict(by_region))\n",
    "\n",
    "# 2. Total per region\n",
    "totals = defaultdict(int)\n",
    "for region, amount in sales:\n",
    "    totals[region] += amount\n",
    "print(dict(totals))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fa70a952",
   "metadata": {},
   "source": [
    "Choose missing-key behavior deliberately:\n",
    "\n",
    "| Operation | If the key is absent | Changes the dictionary? |\n",
    "| --- | --- | --- |\n",
    "| `d[key]` on a regular dictionary | Raises `KeyError` | No |\n",
    "| `d.get(key, default)` | Returns the fallback | No |\n",
    "| `d.setdefault(key, default)` | Inserts and returns the fallback | Yes |\n",
    "| `dd[key]` on a `defaultdict` with a factory | Creates, stores, and returns a factory value | Yes |\n",
    "| `dd.get(key)` | Returns `None` | No |\n",
    "\n",
    "A required field can use bracket access so missing data is visible. An optional field can use `get()`. Grouping can use `setdefault()` or `defaultdict` to create containers as needed."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "id": "ce7ba23b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.860899Z",
     "iopub.status.busy": "2026-10-13T02:11:14.860848Z",
     "iopub.status.idle": "2026-10-13T02:11:14.862263Z",
     "shell.execute_reply": "2026-10-13T02:11:14.862111Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "get: None\n",
      "After get: {}\n",
      "brackets: []\n",
      "After brackets: {'north': []}\n"
     ]
    }
   ],
   "source": [
    "from collections import defaultdict\n",
    "\n",
    "groups = defaultdict(list)\n",
    "print('get:', groups.get('north'))\n",
    "print('After get:', dict(groups))\n",
    "print('brackets:', groups['north'])\n",
    "print('After brackets:', dict(groups))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "99ff79b5",
   "metadata": {},
   "source": [
    "### Invert a Mapping without Losing Data\n",
    "\n",
    "Inverting a dictionary makes its values into keys. Those values must therefore be hashable. If several original keys share a value, collect them in a list so every association survives.\n",
    "\n",
    "For example, count the letters in `parrot`, then group the letters by frequency."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d9d52cdb",
   "metadata": {},
   "source": [
    "```{index} dict; inverting\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "e1327f3a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.862971Z",
     "iopub.status.busy": "2026-10-13T02:11:14.862921Z",
     "iopub.status.idle": "2026-10-13T02:11:14.864522Z",
     "shell.execute_reply": "2026-10-13T02:11:14.864349Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'p': 1, 'a': 1, 'r': 2, 'o': 1, 't': 1}"
      ]
     },
     "execution_count": 31,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "d = value_counts('parrot')\n",
    "d\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "477a7186",
   "metadata": {},
   "source": [
    "If we invert this dictionary, the result should be `{1: ['p', 'a', 'o', 't'], 2: ['r']}`.\n",
    "That means the letters that appear once are `'p'`, `'a'`, `'o'`, and `'t'`, and the letter that appears twice is `'r'`.\n",
    "\n",
    "The following function takes a dictionary and returns its inverse as a new dictionary."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "6be5133d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.865304Z",
     "iopub.status.busy": "2026-10-13T02:11:14.865256Z",
     "iopub.status.idle": "2026-10-13T02:11:14.866624Z",
     "shell.execute_reply": "2026-10-13T02:11:14.866455Z"
    }
   },
   "outputs": [],
   "source": [
    "def invert_dict(d):\n",
    "    new = {}\n",
    "    for key, value in d.items():\n",
    "        if value not in new:\n",
    "            new[value] = [key]\n",
    "        else:\n",
    "            new[value].append(key)\n",
    "    return new\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e67d5033",
   "metadata": {},
   "source": [
    "The `for` loop walks through the keys and values in `d`.\n",
    "If the value is not already in the new dictionary, we create a list with one key.\n",
    "Otherwise we append the key to the existing list.\n",
    "\n",
    "We can test it like this:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "59bf023a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.867344Z",
     "iopub.status.busy": "2026-10-13T02:11:14.867293Z",
     "iopub.status.idle": "2026-10-13T02:11:14.868851Z",
     "shell.execute_reply": "2026-10-13T02:11:14.868673Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{1: ['p', 'a', 'o', 't'], 2: ['r']}"
      ]
     },
     "execution_count": 33,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "invert_dict(d)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch07-invert-comp-text",
   "metadata": {},
   "source": [
    "When every original value is unique and hashable, a comprehension can swap each pair directly."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "id": "ch07-invert-comp",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.869581Z",
     "iopub.status.busy": "2026-10-13T02:11:14.869526Z",
     "iopub.status.idle": "2026-10-13T02:11:14.871173Z",
     "shell.execute_reply": "2026-10-13T02:11:14.871011Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'APL': 'apple', 'BAN': 'banana', 'CHR': 'cherry'}"
      ]
     },
     "execution_count": 34,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "codes = {'apple': 'APL', 'banana': 'BAN', 'cherry': 'CHR'}\n",
    "\n",
    "code_to_fruit = {code: fruit for fruit, code in codes.items()}   ### swap each pair\n",
    "code_to_fruit"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch07-invert-comp-caveat-text",
   "metadata": {},
   "source": [
    "The loop variables `fruit, code` unpack each key-value pair, and the expression `code: fruit` puts them back in reverse order.\n",
    "Now you can look up a fruit by its code, as in `code_to_fruit['BAN']`.\n",
    "\n",
    "This shortcut works only when the values are unique.\n",
    "A dictionary can hold each key only once, so if two keys share a value, the later key overwrites the earlier one.\n",
    "Here is what happens if you swap the letter counts for `parrot`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "ch07-invert-comp-caveat",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.871859Z",
     "iopub.status.busy": "2026-10-13T02:11:14.871815Z",
     "iopub.status.idle": "2026-10-13T02:11:14.873308Z",
     "shell.execute_reply": "2026-10-13T02:11:14.873141Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{1: 't', 2: 'r'}"
      ]
     },
     "execution_count": 35,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "{count: letter for letter, count in d.items()}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch07-invert-comp-choice",
   "metadata": {},
   "source": [
    "The letters `'p'`, `'a'`, and `'o'` are lost, because each later letter with a count of `1` replaced the one before it.\n",
    "Use the comprehension when you know the values are unique, such as ID numbers or product codes.\n",
    "Use `invert_dict` when values can repeat and you need to keep every key."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "id": "a4dcd625",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.874017Z",
     "iopub.status.busy": "2026-10-13T02:11:14.873974Z",
     "iopub.status.idle": "2026-10-13T02:11:14.875228Z",
     "shell.execute_reply": "2026-10-13T02:11:14.875090Z"
    },
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Inverting a Dictionary\n",
    "#   Given the dictionary below that maps student names to grades,\n",
    "#   use invert_dict() to find all students who received each grade.\n",
    "#   Print the inverted dictionary.\n",
    "grades = {'Alice': 'A', 'Bob': 'B', 'Carol': 'A', 'Dave': 'C', 'Eve': 'B'}\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "b47b0632",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.875912Z",
     "iopub.status.busy": "2026-10-13T02:11:14.875861Z",
     "iopub.status.idle": "2026-10-13T02:11:14.877219Z",
     "shell.execute_reply": "2026-10-13T02:11:14.877058Z"
    },
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'A': ['Alice', 'Carol'], 'B': ['Bob', 'Eve'], 'C': ['Dave']}\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "grades = {'Alice': 'A', 'Bob': 'B', 'Carol': 'A', 'Dave': 'C', 'Eve': 'B'}\n",
    "print(invert_dict(grades))\n",
    "# {'A': ['Alice', 'Carol'], 'B': ['Bob', 'Eve'], 'C': ['Dave']}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "93788424",
   "metadata": {},
   "source": [
    "### Sorting Dictionaries\n",
    "\n",
    "Sometimes you want to sort dictionary items by their values rather than their keys.\n",
    "We can define a small helper that returns the second element of a `(key, value)` pair.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d4b238ee",
   "metadata": {},
   "source": [
    "```{index} dict; sorting by value\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "id": "2c2719de",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.877891Z",
     "iopub.status.busy": "2026-10-13T02:11:14.877846Z",
     "iopub.status.idle": "2026-10-13T02:11:14.879013Z",
     "shell.execute_reply": "2026-10-13T02:11:14.878846Z"
    }
   },
   "outputs": [],
   "source": [
    "def second_element(t):\n",
    "    return t[1]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "98aa3bc0",
   "metadata": {},
   "source": [
    "Then we pass that function as the optional `key` argument to `sorted`.\n",
    "The `key` function computes a **sort key** for each item."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "id": "fd184915",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.879716Z",
     "iopub.status.busy": "2026-10-13T02:11:14.879656Z",
     "iopub.status.idle": "2026-10-13T02:11:14.881220Z",
     "shell.execute_reply": "2026-10-13T02:11:14.881050Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[('p', 1), ('a', 1), ('o', 1), ('t', 1), ('r', 2)]"
      ]
     },
     "execution_count": 39,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "counter = value_counts('parrot')\n",
    "items = counter.items()\n",
    "sorted_items = sorted(items, key=second_element)\n",
    "sorted_items\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "004449d3",
   "metadata": {},
   "source": [
    "The sort key determines the order.\n",
    "The letter with the lowest count appears first, and the highest count appears last.\n",
    "So we can find the most common letter like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "id": "497d3e95",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.881994Z",
     "iopub.status.busy": "2026-10-13T02:11:14.881936Z",
     "iopub.status.idle": "2026-10-13T02:11:14.883379Z",
     "shell.execute_reply": "2026-10-13T02:11:14.883248Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "('r', 2)"
      ]
     },
     "execution_count": 40,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "sorted_items[-1]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3e30ff15",
   "metadata": {},
   "source": [
    "If we only want the maximum, we don't have to sort the list.\n",
    "We can use `max`, which also accepts a `key` function."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "id": "403e241b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.884054Z",
     "iopub.status.busy": "2026-10-13T02:11:14.884012Z",
     "iopub.status.idle": "2026-10-13T02:11:14.885401Z",
     "shell.execute_reply": "2026-10-13T02:11:14.885267Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "('r', 2)"
      ]
     },
     "execution_count": 41,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "max(items, key=second_element)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "id": "cfe03b1a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.886272Z",
     "iopub.status.busy": "2026-10-13T02:11:14.886220Z",
     "iopub.status.idle": "2026-10-13T02:11:14.887437Z",
     "shell.execute_reply": "2026-10-13T02:11:14.887297Z"
    },
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Sorting by Value\n",
    "#   1. Count the letter frequencies in the word 'mississippi'.\n",
    "#   2. Sort the resulting items by frequency (value), ascending.\n",
    "#   3. Print the letter with the highest frequency using max() with a key function.\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "id": "493a923d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.888109Z",
     "iopub.status.busy": "2026-10-13T02:11:14.888064Z",
     "iopub.status.idle": "2026-10-13T02:11:14.889480Z",
     "shell.execute_reply": "2026-10-13T02:11:14.889331Z"
    },
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[('m', 1), ('p', 2), ('i', 4), ('s', 4)]\n",
      "i\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "counter = value_counts('mississippi')\n",
    "items = counter.items()\n",
    "\n",
    "def second_element(t):\n",
    "    return t[1]\n",
    "\n",
    "print(sorted(items, key=second_element))   # sorted by frequency ascending\n",
    "print(max(items, key=second_element)[0])   # i, the most frequent letter\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a5714128",
   "metadata": {},
   "source": [
    "For tied counts, `max()` returns the first maximal item encountered; sorting is stable, so equal-count items keep their input order. In `mississippi`, both `i` and `s` appear four times. A report should make its tie policy explicit. `max()` requires at least one item unless you supply a `default`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "812df2d0",
   "metadata": {},
   "source": [
    "## Modeling Records and Compound Keys\n",
    "\n",
    "### Choose Hashable Keys\n",
    "\n",
    "```{index} hashable keys, hash value\n",
    "```\n",
    "\n",
    "A **hashable** object has a hash value that stays stable during its lifetime, and equal objects must have equal hashes. Dictionaries use the hash to narrow the search, then compare keys for equality. Different keys may share a hash, so a hash is not a unique identifier.\n",
    "\n",
    "Strings and numbers are familiar hashable keys. Lists, dictionaries, and sets are not hashable. A tuple is hashable only when all of its elements are hashable. Hashability and immutability are related, but they are not interchangeable rules for every Python object.\n",
    "\n",
    "Choose keys that identify the thing you need to retrieve: a student ID for one record, a course code for one roster, or a tuple for a combination of fields. Values can be mutable objects, including lists and dictionaries."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0ce39761",
   "metadata": {},
   "source": [
    "A hash value is just an integer that represents an object, computed by the `hash()` function. \n",
    "\n",
    "| Type(s) | Mutability/Conditional | Hashable | Example |\n",
    "|---|---|---|---|\n",
    "| `int`, `float`, `bool`, `complex` | Immutable | Yes | `42`, `3.14`, `True`, `2+3j` |\n",
    "| `str` | Immutable | Yes | `\"hello\"` |\n",
    "| `tuple` | Immutable, conditional on all elements being hashable | Yes (conditional) | `(1, \"a\")` yes, `([1], \"a\")` no |\n",
    "| `frozenset` | Immutable, conditional on all elements being hashable | Yes (conditional) | `frozenset({1, 2})` |\n",
    "| `bytes` | Immutable | Yes | `b\"abc\"` |\n",
    "| `None` | Immutable singleton | Yes | `None` |\n",
    "| Functions, classes | Identity-based objects | Yes (by identity) | `len`, `dict` |\n",
    "| `list` | Mutable | No | `[1, 2, 3]` |\n",
    "| `dict` | Mutable | No | `{\"a\": 1}` |\n",
    "| `set` | Mutable | No | `{1, 2, 3}` |\n",
    "| `bytearray` | Mutable | No | `bytearray(b\"abc\")` |\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "695c64f1",
   "metadata": {},
   "source": [
    "Here are a few quick checks. Equal tuples have equal hashes, and tuples of hashable elements are hashable."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "id": "2dc68833",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.890222Z",
     "iopub.status.busy": "2026-10-13T02:11:14.890177Z",
     "iopub.status.idle": "2026-10-13T02:11:14.891701Z",
     "shell.execute_reply": "2026-10-13T02:11:14.891563Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "7267574591690527098"
      ]
     },
     "execution_count": 44,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a = (1, 2)\n",
    "b = (1, 2)\n",
    "a == b, hash(a) == hash(b)      ### return True, True\n",
    "\n",
    "hash((1, (2, 3)))               ###  hashes a nested tuple, returning the large number shown"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "id": "27c09ce8",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.892377Z",
     "iopub.status.busy": "2026-10-13T02:11:14.892332Z",
     "iopub.status.idle": "2026-10-13T02:11:14.894013Z",
     "shell.execute_reply": "2026-10-13T02:11:14.893850Z"
    }
   },
   "outputs": [
    {
     "ename": "TypeError",
     "evalue": "unhashable type: 'list'",
     "output_type": "error",
     "traceback": [
      "\u001b[31mTypeError\u001b[39m\u001b[31m:\u001b[39m unhashable type: 'list'\n"
     ]
    }
   ],
   "source": [
    "%%expect TypeError\n",
    "mixed = (1, [2, 3])\n",
    "d = {mixed: 'not hashable'}\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch07-nested-dicts",
   "metadata": {},
   "source": [
    "### Store Nested Records\n",
    "\n",
    "A dictionary stored as a value inside another dictionary is a **nested dictionary**. Nesting groups related fields, such as a student record containing several grades. JSON objects can also be represented with dictionaries.\n",
    "\n",
    "To reach an inner value, chain the keys: the outer key first, then the inner key."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch07-nested-dicts-index",
   "metadata": {},
   "source": [
    "```{index} nested dictionary, record\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "id": "ch07-nested-access",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.894666Z",
     "iopub.status.busy": "2026-10-13T02:11:14.894622Z",
     "iopub.status.idle": "2026-10-13T02:11:14.895958Z",
     "shell.execute_reply": "2026-10-13T02:11:14.895822Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'math': 88, 'science': 92}\n",
      "88\n"
     ]
    }
   ],
   "source": [
    "student = {\n",
    "    \"name\": \"Alice\",\n",
    "    \"grades\": {\"math\": 88, \"science\": 92},\n",
    "    \"clubs\": [\"robotics\"],\n",
    "}\n",
    "\n",
    "print(student[\"grades\"])             # the inner dictionary\n",
    "print(student[\"grades\"][\"math\"])     # 88"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch07-nested-update-text",
   "metadata": {},
   "source": [
    "Read the chain from left to right, one level at a time: `student[\"grades\"]` evaluates to the inner dictionary, and `[\"math\"]` is then applied to that inner dictionary.\n",
    "\n",
    "To change the inner dictionary, reach it the same way and then use any dictionary operation on it. Because `student[\"grades\"]` *is* the inner dictionary, not a copy, the change is visible through `student`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "id": "ch07-nested-update",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.896589Z",
     "iopub.status.busy": "2026-10-13T02:11:14.896545Z",
     "iopub.status.idle": "2026-10-13T02:11:14.897840Z",
     "shell.execute_reply": "2026-10-13T02:11:14.897687Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'math': 90, 'science': 92, 'history': 78}\n"
     ]
    }
   ],
   "source": [
    "grades = student[\"grades\"]                   ### an alias for the inner dict, not a copy\n",
    "grades[\"math\"] = 90                          ### update an existing inner key\n",
    "student[\"grades\"].update({\"history\": 78})    ### add a new inner key\n",
    "\n",
    "print(student[\"grades\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch07-nested-defaults-text",
   "metadata": {},
   "source": [
    "A missing key can occur at either level, so each level needs its own protection. Call `get()` on the dictionary at the level where the key might be missing, and use `setdefault()` to create a missing inner container before you add to it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "id": "ch07-nested-defaults",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.898529Z",
     "iopub.status.busy": "2026-10-13T02:11:14.898483Z",
     "iopub.status.idle": "2026-10-13T02:11:14.900074Z",
     "shell.execute_reply": "2026-10-13T02:11:14.899942Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "none assigned\n",
      "no grade\n",
      "{'city': 'Austin'}\n",
      "history: 78\n",
      "math: 90\n",
      "science: 92\n"
     ]
    }
   ],
   "source": [
    "### missing outer key: .get() on student returns the default instead of raising KeyError\n",
    "print(student.get(\"advisor\", \"none assigned\"))\n",
    "\n",
    "### missing inner key: call .get() on the inner dictionary\n",
    "print(student[\"grades\"].get(\"art\", \"no grade\"))\n",
    "\n",
    "### create the inner dictionary only if it is missing, then add to it\n",
    "student.setdefault(\"contact\", {})[\"city\"] = \"Austin\"\n",
    "print(student[\"contact\"])\n",
    "\n",
    "### loop through the inner dictionary in sorted key order\n",
    "for subject in sorted(student[\"grades\"]):\n",
    "    print(f\"{subject}: {student['grades'][subject]}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "id": "ch07-nested-ex",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.900741Z",
     "iopub.status.busy": "2026-10-13T02:11:14.900689Z",
     "iopub.status.idle": "2026-10-13T02:11:14.902010Z",
     "shell.execute_reply": "2026-10-13T02:11:14.901865Z"
    },
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Nested Dictionaries\n",
    "#   The nested dictionary below maps each fruit to an inner dictionary of details.\n",
    "#   1. Use chained access to print the stock of 'banana'.\n",
    "#   2. Change the price of 'apple' to 1.25, add the inner key 'color' with the\n",
    "#      value 'red' to the 'apple' dictionary, and print inventory['apple'].\n",
    "#   3. Print the 'discount' of 'banana', using 0 as the default, without raising KeyError.\n",
    "inventory = {\n",
    "    'apple': {'price': 1.20, 'stock': 15},\n",
    "    'banana': {'price': 0.50, 'stock': 4},\n",
    "}\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "id": "ch07-nested-sol",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.902788Z",
     "iopub.status.busy": "2026-10-13T02:11:14.902715Z",
     "iopub.status.idle": "2026-10-13T02:11:14.904264Z",
     "shell.execute_reply": "2026-10-13T02:11:14.904111Z"
    },
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "4\n",
      "{'price': 1.25, 'stock': 15, 'color': 'red'}\n",
      "0\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "inventory = {\n",
    "    'apple': {'price': 1.20, 'stock': 15},\n",
    "    'banana': {'price': 0.50, 'stock': 4},\n",
    "}\n",
    "\n",
    "# 1. Chained access: outer key, then inner key\n",
    "print(inventory['banana']['stock'])            # 4\n",
    "\n",
    "# 2. Update the inner dictionary in place\n",
    "inventory['apple']['price'] = 1.25\n",
    "inventory['apple']['color'] = 'red'\n",
    "print(inventory['apple'])\n",
    "\n",
    "# 3. Default for a missing inner key\n",
    "print(inventory['banana'].get('discount', 0))  # 0"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c3d3536f",
   "metadata": {},
   "source": [
    "### Copy Records without Sharing Inner Containers by Accident\n",
    "\n",
    "```{index} dictionary copy, shallow copy, dict.fromkeys()\n",
    "```\n",
    "\n",
    "Assignment creates an alias. `dict(record)` and `record.copy()` create a new outer dictionary, but they are **shallow copies**: inner lists and dictionaries are still shared. Predict which record changes before running this example."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "id": "95f360e4",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.904964Z",
     "iopub.status.busy": "2026-10-13T02:11:14.904919Z",
     "iopub.status.idle": "2026-10-13T02:11:14.906371Z",
     "shell.execute_reply": "2026-10-13T02:11:14.906228Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Original: {'math': 95}\n",
      "Copy: {'math': 95}\n",
      "Shared inner dictionary: True\n"
     ]
    }
   ],
   "source": [
    "student = {'name': 'Ana', 'grades': {'math': 91}}\n",
    "copy_of_student = student.copy()\n",
    "copy_of_student['grades']['math'] = 95\n",
    "print('Original:', student['grades'])\n",
    "print('Copy:', copy_of_student['grades'])\n",
    "print('Shared inner dictionary:', student['grades'] is copy_of_student['grades'])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2978096a",
   "metadata": {},
   "source": [
    "For this record shape, copy the inner grades dictionary too when the grades must be independent. More deeply nested structures need a deliberate copying strategy; an outer copy alone cannot isolate them."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "id": "cc050f5a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.907208Z",
     "iopub.status.busy": "2026-10-13T02:11:14.907156Z",
     "iopub.status.idle": "2026-10-13T02:11:14.908728Z",
     "shell.execute_reply": "2026-10-13T02:11:14.908530Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Original: {'math': 91}\n",
      "Independent: {'math': 95}\n"
     ]
    }
   ],
   "source": [
    "student = {'name': 'Ana', 'grades': {'math': 91}}\n",
    "independent = student.copy()\n",
    "independent['grades'] = student['grades'].copy()\n",
    "independent['grades']['math'] = 95\n",
    "print('Original:', student['grades'])\n",
    "print('Independent:', independent['grades'])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "40c6899e",
   "metadata": {},
   "source": [
    "Replacing an outer entry and mutating an inner object are different operations. `copy_of_student['grades'] = {...}` changes only the copied dictionary's entry; `copy_of_student['grades']['math'] = 95` changes the shared inner dictionary.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3dd26e65",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Make an Independent Grade Record *(applied)*\n",
    "# 1. Make a shallow copy named revised from student.\n",
    "# 2. Copy the inner grades dictionary so the records no longer share it.\n",
    "# 3. Set revised's math grade to 95, leaving student's math grade at 91.\n",
    "# 4. Print both grades and whether the two inner dictionaries are the same object.\n",
    "student = {'name': 'Ana', 'grades': {'math': 91}}\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "00b1602e",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Original math: 91\n",
      "Revised math: 95\n",
      "Shared grades: False\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "student = {'name': 'Ana', 'grades': {'math': 91}}\n",
    "revised = student.copy()\n",
    "revised['grades'] = student['grades'].copy()\n",
    "revised['grades']['math'] = 95\n",
    "print('Original math:', student['grades']['math'])\n",
    "print('Revised math:', revised['grades']['math'])\n",
    "print('Shared grades:', student['grades'] is revised['grades'])\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e3d4eba3",
   "metadata": {},
   "source": [
    "`dict.fromkeys(names, [])` has a related trap: every key receives the same list object. A comprehension evaluates `[]` separately for each key."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "id": "223ec829",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.909532Z",
     "iopub.status.busy": "2026-10-13T02:11:14.909477Z",
     "iopub.status.idle": "2026-10-13T02:11:14.911025Z",
     "shell.execute_reply": "2026-10-13T02:11:14.910864Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Shared lists: {'Ana': [91], 'Ben': [91]}\n",
      "Separate lists: {'Ana': [91], 'Ben': []}\n"
     ]
    }
   ],
   "source": [
    "names = ['Ana', 'Ben']\n",
    "shared_grades = dict.fromkeys(names, [])\n",
    "shared_grades['Ana'].append(91)\n",
    "print('Shared lists:', shared_grades)\n",
    "\n",
    "separate_grades = {name: [] for name in names}\n",
    "separate_grades['Ana'].append(91)\n",
    "print('Separate lists:', separate_grades)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "id": "f3f36048",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.911734Z",
     "iopub.status.busy": "2026-10-13T02:11:14.911672Z",
     "iopub.status.idle": "2026-10-13T02:11:14.912884Z",
     "shell.execute_reply": "2026-10-13T02:11:14.912734Z"
    },
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Repair Shared Grade Lists *(applied)*\n",
    "# Predict why adding a grade for Ana also changes Ben.\n",
    "# Replace the construction so each student gets an independent list.\n",
    "# Append 91 for Ana and print both students' lists.\n",
    "# Faulty construction: grades = dict.fromkeys(names, [])\n",
    "names = ['Ana', 'Ben']\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "id": "c1a02aac",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.913543Z",
     "iopub.status.busy": "2026-10-13T02:11:14.913497Z",
     "iopub.status.idle": "2026-10-13T02:11:14.914905Z",
     "shell.execute_reply": "2026-10-13T02:11:14.914732Z"
    },
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'Ana': [91], 'Ben': []}\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "names = ['Ana', 'Ben']\n",
    "grades = {name: [] for name in names}\n",
    "grades['Ana'].append(91)\n",
    "print(grades)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cc490880",
   "metadata": {},
   "source": [
    "### Use Tuple Keys for Compound Lookup\n",
    "\n",
    "```{index} tuple; as dict key\n",
    "```\n",
    "\n",
    "A tuple key combines fields into one lookup. A `(name, subject)` key is useful when you often retrieve one score by both fields. A nested dictionary keyed first by student is useful when you often retrieve all of a student's grades. Choose the shape to match the lookup you need."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch07-tuple-keys-example-text",
   "metadata": {},
   "source": [
    "Because a tuple of strings is hashable, you can use it as a key to look up a value by two pieces of information at once.\n",
    "The dictionary below maps a `(name, subject)` pair to a test score.\n",
    "To look up a score, you pass the whole tuple as the key:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "id": "ch07-tuple-keys-example",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.915642Z",
     "iopub.status.busy": "2026-10-13T02:11:14.915589Z",
     "iopub.status.idle": "2026-10-13T02:11:14.917155Z",
     "shell.execute_reply": "2026-10-13T02:11:14.917000Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "91"
      ]
     },
     "execution_count": 56,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "scores = {\n",
    "    ('Ana', 'math'): 91,\n",
    "    ('Ana', 'science'): 84,\n",
    "    ('Ben', 'math'): 77,\n",
    "}\n",
    "\n",
    "scores[('Ana', 'math')]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch07-tuple-keys-loop-text",
   "metadata": {},
   "source": [
    "When you loop over `items()`, each key comes back as a tuple.\n",
    "You can unpack that tuple into separate variables inside the loop, the same way you unpack any other tuple:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "id": "ch07-tuple-keys-loop",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.917804Z",
     "iopub.status.busy": "2026-10-13T02:11:14.917752Z",
     "iopub.status.idle": "2026-10-13T02:11:14.919300Z",
     "shell.execute_reply": "2026-10-13T02:11:14.919061Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Ana math 91\n",
      "Ana science 84\n",
      "Ben math 77\n"
     ]
    }
   ],
   "source": [
    "for key, score in scores.items():\n",
    "    name, subject = key          ### unpack the tuple key\n",
    "    print(name, subject, score)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch07-tuple-keys-nested-text",
   "metadata": {},
   "source": [
    "You can also unpack the key in the loop header itself.\n",
    "Each item from `items()` has the shape `((name, subject), score)`, a tuple key followed by a value.\n",
    "Writing the loop variables as `(name, subject), score` matches that shape, so Python unpacks both levels in one step:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "id": "ch07-tuple-keys-nested",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.920215Z",
     "iopub.status.busy": "2026-10-13T02:11:14.920157Z",
     "iopub.status.idle": "2026-10-13T02:11:14.921526Z",
     "shell.execute_reply": "2026-10-13T02:11:14.921372Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Ana scored 91 in math\n",
      "Ana scored 84 in science\n",
      "Ben scored 77 in math\n"
     ]
    }
   ],
   "source": [
    "for (name, subject), score in scores.items():\n",
    "    print(f'{name} scored {score} in {subject}')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "id": "11366860",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.922208Z",
     "iopub.status.busy": "2026-10-13T02:11:14.922158Z",
     "iopub.status.idle": "2026-10-13T02:11:14.923345Z",
     "shell.execute_reply": "2026-10-13T02:11:14.923196Z"
    },
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Hashable Tuples\n",
    "#   1. Create a dictionary that uses tuples as keys to map (row, col) grid positions\n",
    "#      to string values: (0,0)->'start', (1,2)->'middle', (2,2)->'end'.\n",
    "#   2. Print the value at position (1, 2).\n",
    "#   3. Try to use ([0, 0],) as a key — wrap it in a try/except and print the error type.\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 60,
   "id": "ebc0cf63",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.924038Z",
     "iopub.status.busy": "2026-10-13T02:11:14.923989Z",
     "iopub.status.idle": "2026-10-13T02:11:14.925492Z",
     "shell.execute_reply": "2026-10-13T02:11:14.925351Z"
    },
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "middle\n",
      "TypeError unhashable type: 'list'\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "grid = {(0,0): 'start', (1,2): 'middle', (2,2): 'end'}\n",
    "print(grid[(1, 2)])    # 'middle'\n",
    "\n",
    "try:\n",
    "    bad = {([0, 0],): 'unhashable'}\n",
    "except TypeError as e:\n",
    "    print(type(e).__name__, e)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "38b4c833",
   "metadata": {},
   "source": [
    "### Accumulate and Filter a Report\n",
    "\n",
    "```{index} accumulator pattern, filtering\n",
    "```\n",
    "\n",
    "An **accumulator** stores results collected during a loop. **Filtering** keeps only entries that satisfy a condition. A stock report can accumulate a total while collecting names of low-stock fruits. The input remains a dictionary; the output can be a number, a list, or another dictionary."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 61,
   "id": "2368e88f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.926195Z",
     "iopub.status.busy": "2026-10-13T02:11:14.926148Z",
     "iopub.status.idle": "2026-10-13T02:11:14.927564Z",
     "shell.execute_reply": "2026-10-13T02:11:14.927428Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Total units: 19\n",
      "Low stock: ['banana', 'cherry']\n"
     ]
    }
   ],
   "source": [
    "stock = {'apple': 15, 'banana': 4, 'cherry': 0}\n",
    "total = 0\n",
    "low_stock = []\n",
    "for fruit, units in stock.items():\n",
    "    total += units\n",
    "    if units < 10:\n",
    "        low_stock.append(fruit)\n",
    "print('Total units:', total)\n",
    "print('Low stock:', low_stock)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 62,
   "id": "ch07-accum-ex",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.928190Z",
     "iopub.status.busy": "2026-10-13T02:11:14.928144Z",
     "iopub.status.idle": "2026-10-13T02:11:14.929390Z",
     "shell.execute_reply": "2026-10-13T02:11:14.929251Z"
    },
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Accumulate and Filter\n",
    "#   The dictionary below maps each fruit to the number of units in stock.\n",
    "#   1. Loop through stock and use a counter to count the fruits with fewer than 10 units.\n",
    "#   2. In the same loop, use a list as an accumulator to collect the names of those fruits.\n",
    "#   3. Use a running total to add up the units of all fruits.\n",
    "#   Print the count, the list, and the total.\n",
    "stock = {'apple': 15, 'banana': 4, 'cherry': 0, 'date': 22, 'grape': 7}\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "id": "ch07-accum-sol",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.930100Z",
     "iopub.status.busy": "2026-10-13T02:11:14.930054Z",
     "iopub.status.idle": "2026-10-13T02:11:14.931665Z",
     "shell.execute_reply": "2026-10-13T02:11:14.931505Z"
    },
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3\n",
      "['banana', 'cherry', 'grape']\n",
      "48\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "stock = {'apple': 15, 'banana': 4, 'cherry': 0, 'date': 22, 'grape': 7}\n",
    "\n",
    "low_count = 0\n",
    "low_stock = []\n",
    "total = 0\n",
    "\n",
    "for fruit, units in stock.items():\n",
    "    if units < 10:\n",
    "        low_count += 1\n",
    "        low_stock.append(fruit)\n",
    "    total += units\n",
    "\n",
    "print(low_count)    # 3\n",
    "print(low_stock)    # ['banana', 'cherry', 'grape']\n",
    "print(total)        # 48"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "73ee46e6",
   "metadata": {},
   "source": [
    "(dict-bigo)=\n",
    "## Lookup Performance\n",
    "\n",
    "```{index} hash table, Big O notation\n",
    "```\n",
    "\n",
    "A **hash table** uses a key's hash to locate candidate entries efficiently. **Big O notation** describes how work grows as the number of entries, *n*, increases. Dictionary key lookup and set membership take average O(1) time: the expected work stays roughly constant as *n* grows. Collisions can make the worst case O(n). List membership can inspect up to *n* elements, so its worst case is O(n).\n",
    "\n",
    "List indexing, such as `nums[0]`, is also O(1). The comparison here is membership search, not every operation on a list.\n",
    "\n",
    "This optional timing experiment repeats the same missing-key lookup at several sizes. Construction happens outside the measured operation. The result illustrates growth; exact times vary by machine."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 64,
   "id": "e349df69",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:14.932425Z",
     "iopub.status.busy": "2026-10-13T02:11:14.932372Z",
     "iopub.status.idle": "2026-10-13T02:11:15.062751Z",
     "shell.execute_reply": "2026-10-13T02:11:15.062322Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Size   list microseconds   dict microseconds\n",
      "  100              0.344              0.016\n",
      " 1000              3.446              0.016\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "10000             34.476              0.016\n"
     ]
    }
   ],
   "source": [
    "from timeit import repeat\n",
    "\n",
    "print('Size   list microseconds   dict microseconds')\n",
    "for n in (100, 1_000, 10_000):\n",
    "    values = list(range(n))\n",
    "    lookup = dict.fromkeys(values)\n",
    "    target = -1  # absent: list membership must scan every element\n",
    "    repetitions = 1_000\n",
    "    list_seconds = min(repeat(lambda: target in values, number=repetitions, repeat=3))\n",
    "    dict_seconds = min(repeat(lambda: target in lookup, number=repetitions, repeat=3))\n",
    "    print(f'{n:5d}  {list_seconds / repetitions * 1e6:17.3f}  '\n",
    "          f'{dict_seconds / repetitions * 1e6:17.3f}')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d938c2f7",
   "metadata": {},
   "source": [
    "Building a dictionary or set also takes time and memory. Creating one for a single lookup may not help; reusing it for many lookups is often useful. When you only need membership and no associated values, use a set, as in the next section."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "id": "518de41c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:15.064548Z",
     "iopub.status.busy": "2026-10-13T02:11:15.064383Z",
     "iopub.status.idle": "2026-10-13T02:11:15.066779Z",
     "shell.execute_reply": "2026-10-13T02:11:15.066195Z"
    },
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Dictionary vs. List Lookup\n",
    "# Given the list of fruits below:\n",
    "# 1. Create a dictionary with fruits as keys and 1 as values using dict comprehension.\n",
    "# 2. Use the `in` operator to check if 'cherry' is in:\n",
    "#    a) the list  b) the dictionary\n",
    "# 3. Print both results.\n",
    "fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry']\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 66,
   "id": "6ff7ed63",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:15.068786Z",
     "iopub.status.busy": "2026-10-13T02:11:15.068673Z",
     "iopub.status.idle": "2026-10-13T02:11:15.070701Z",
     "shell.execute_reply": "2026-10-13T02:11:15.070329Z"
    },
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n",
      "True\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "\n",
    "fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry']\n",
    "\n",
    "# 1. Build lookup dictionary\n",
    "fruit_dict = {fruit: 1 for fruit in fruits}\n",
    "\n",
    "# 2 & 3. Check membership and print\n",
    "print('cherry' in fruits)       # True -- linear search\n",
    "print('cherry' in fruit_dict)   # True -- hash lookup (O(1))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "977ecb75",
   "metadata": {},
   "source": [
    "## Optional Extension: Dictionaries as Memory\n",
    "\n",
    "In {doc}`4.3 Recursion <../04-functions/0403-recursion>`, memoization stored computed Fibonacci results in a dictionary. This review connects that earlier algorithm to key lookup: a known argument maps to its result. Complete the record and grouping patterns before returning to this extension."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "606e347a",
   "metadata": {},
   "source": [
    "```{index} memoization, memo\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 67,
   "id": "df6ddd7c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:15.071897Z",
     "iopub.status.busy": "2026-10-13T02:11:15.071810Z",
     "iopub.status.idle": "2026-10-13T02:11:15.073247Z",
     "shell.execute_reply": "2026-10-13T02:11:15.073002Z"
    }
   },
   "outputs": [],
   "source": [
    "def fibonacci(n):\n",
    "    if n == 0:\n",
    "        return 0\n",
    "    \n",
    "    if n == 1:\n",
    "        return 1\n",
    "\n",
    "    return fibonacci(n-1) + fibonacci(n-2)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "793a7fe6",
   "metadata": {},
   "source": [
    "Furthermore, the run time increases quickly.\n",
    "To understand why, consider the following figure, which shows the **call graph** for\n",
    "`fibonacci` with `n=4`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 68,
   "id": "4b55f9ea",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:15.075361Z",
     "iopub.status.busy": "2026-10-13T02:11:15.075204Z",
     "iopub.status.idle": "2026-10-13T02:11:15.078601Z",
     "shell.execute_reply": "2026-10-13T02:11:15.077528Z"
    }
   },
   "outputs": [],
   "source": [
    "from shared.diagram import make_binding, Frame, Arrow\n",
    "\n",
    "bindings = [make_binding('n', i) for i in range(5)]\n",
    "frames = [Frame([binding]) for binding in bindings]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 69,
   "id": "778ffd57",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:15.081076Z",
     "iopub.status.busy": "2026-10-13T02:11:15.080915Z",
     "iopub.status.idle": "2026-10-13T02:11:15.084421Z",
     "shell.execute_reply": "2026-10-13T02:11:15.083973Z"
    }
   },
   "outputs": [],
   "source": [
    "arrowprops = dict(arrowstyle=\"-\", color='gray', alpha=0.5, ls='-', lw=0.5)\n",
    "\n",
    "def left_arrow(ax, bbox1, bbox2):\n",
    "    x = bbox1.xmin + 0.1\n",
    "    y = bbox1.ymin\n",
    "    dx = bbox2.xmax - x - 0.1\n",
    "    dy = bbox2.ymax - y\n",
    "    arrow = Arrow(dx=dx, dy=dy, arrowprops=arrowprops)\n",
    "    return arrow.draw(ax, x, y)\n",
    "\n",
    "def right_arrow(ax, bbox1, bbox2):\n",
    "    x = bbox1.xmax - 0.1\n",
    "    y = bbox1.ymin\n",
    "    dx = bbox2.xmin - x + 0.1\n",
    "    dy = bbox2.ymax - y\n",
    "    arrow = Arrow(dx=dx, dy=dy, arrowprops=arrowprops)\n",
    "    return arrow.draw(ax, x, y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 70,
   "id": "72487676",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:15.085747Z",
     "iopub.status.busy": "2026-10-13T02:11:15.085670Z",
     "iopub.status.idle": "2026-10-13T02:11:15.180117Z",
     "shell.execute_reply": "2026-10-13T02:11:15.179630Z"
    }
   },
   "outputs": [
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAgIAAADsCAYAAAAGlM4XAAAAOnRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjEwLjcsIGh0dHBzOi8vbWF0cGxvdGxpYi5vcmcvTLEjVAAAAAlwSFlzAAAPYQAAD2EBqD+naQAAEwJJREFUeJzt3d9rU/cfx/F3Y3+nqY22tlLnBEF6YREvVJigvZBZRFAvqhvCmDCGDJx6oRf+A4OtDBRRdjehKzjsoChbpYiVgWO9mOhFHZu6Tmy11hq19ocamy/v86Xi1NokJjk5n/fzAcG2VPLp+eQkr/P+/DgFiUQiIQAAwKSQ3w0AAAD+IQgAAGAYQQAAAMMIAgAAGEYQAADAMIIAAACGEQQAADCMIAAAgGEEAQAADCMIAABgGEEAAADDCAIAABhGEAAAwDCCAAAAhhEEAAAwjCAAAIBhBAEAAAwjCAAAYBhBAAAAwwr9bgCA7BsdHeUwJyESiXCcYA4VAQAADCMIAABgGEEAAADDCAIAABhGEAAAwDCCAAAAhhEEAAAwjCAAAIBhBAEAAA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jxeFz8UlNTI+FwWLq6uuTEiRNJfWDAzf69deuW1NbWSmHh/++3VVBQIIsWLfJ+DgAWJX33wVRt377d+3fZsmXem+7Q0NBrV9q9vb0yODgouaLPH4vFvA+Mc+fOSUtLi9TV1eXs+V1C/wKAG7JaEXjxJKGQr1eMyLyg9q9e/WsonW5vIpHwqgH6cwCwKGsVgWSsXr06J88zNjYm3d3d3lhwNBqVdevWSUNDg/cBBlv9q8MIK1askJMnT8rOnTuls7PTqxQtXbo0J20FgHzjaxDIFZ0gNj4+Ls3NzbMGgL1793qrBvSqcdu2bVJRUSGXL1/OaXuRvf5Vhw8f9lYK6IRHnfh47NgxDjkAswoSWhtNwujoaPZb44BIJCJBRP+63b8AMBNq4wAAGEYQAADAMIIAAACGEQQAADCMIAAAgGEEAQAADCMIAABgGEEAAADDCAIAABhGEAAAwDCCAAAAhiV9rwEAAOAeKgIAABhGEAAAwDCCAAAAhhEEAAAwjCAAAIBhBAEAAAwjCAAAYBhBAAAAwwgCAAAYRhAAAMAwggAAAIYRBAAAMIwgAACAYQQBAAAMIwgAAGAYQQAAAMMIAgAAGEYQAADAMIIAAACGEQQAABC7/gdWh2GfnVoXnQAAAABJRU5ErkJggg==",
      "text/plain": [
       "<Figure size 494x216 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from shared.diagram import diagram, adjust, Bbox\n",
    "\n",
    "width, height, x, y = [4.94, 2.16, -1.03, 1.91]\n",
    "ax = diagram(width, height)\n",
    "\n",
    "dx = 0.6\n",
    "dy = 0.55\n",
    "\n",
    "bboxes = []\n",
    "bboxes.append(frames[4].draw(ax, x+6*dx, y))\n",
    "\n",
    "bboxes.append(frames[3].draw(ax, x+4*dx, y-dy))\n",
    "bboxes.append(frames[2].draw(ax, x+8*dx, y-dy))\n",
    "\n",
    "bboxes.append(frames[2].draw(ax, x+3*dx, y-2*dy))\n",
    "bboxes.append(frames[1].draw(ax, x+5*dx, y-2*dy))\n",
    "bboxes.append(frames[1].draw(ax, x+7*dx, y-2*dy))\n",
    "bboxes.append(frames[0].draw(ax, x+9*dx, y-2*dy))\n",
    "\n",
    "bboxes.append(frames[1].draw(ax, x+2*dx, y-3*dy))\n",
    "bboxes.append(frames[0].draw(ax, x+4*dx, y-3*dy))\n",
    "\n",
    "left_arrow(ax, bboxes[0], bboxes[1])\n",
    "left_arrow(ax, bboxes[1], bboxes[3])\n",
    "left_arrow(ax, bboxes[3], bboxes[7])\n",
    "left_arrow(ax, bboxes[2], bboxes[5])\n",
    "\n",
    "right_arrow(ax, bboxes[0], bboxes[2])\n",
    "right_arrow(ax, bboxes[1], bboxes[4])\n",
    "right_arrow(ax, bboxes[2], bboxes[6])\n",
    "right_arrow(ax, bboxes[3], bboxes[8])\n",
    "\n",
    "bbox = Bbox.union(bboxes)\n",
    "# adjust(x, y, bbox)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "847dad78",
   "metadata": {},
   "source": [
    "A call graph shows a set of function frames, with lines connecting each frame to the frames of the functions it calls.\n",
    "At the top of the graph, `fibonacci` with `n=4` calls `fibonacci` with ` n=3` and `n=2`.\n",
    "In turn, `fibonacci` with `n=3` calls `fibonacci` with `n=2` and `n=1`. And so on.\n",
    "\n",
    "Count how many times `fibonacci(0)` and `fibonacci(1)` are called. \n",
    "This is an inefficient solution to the problem, and it gets worse as the argument gets bigger.\n",
    "\n",
    "The fix from 4.3 is to keep track of values that have already been computed by storing them in a dictionary, where each stored result is a memo.\n",
    "Here is the memoized version again:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 71,
   "id": "095c569b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:15.182788Z",
     "iopub.status.busy": "2026-10-13T02:11:15.182566Z",
     "iopub.status.idle": "2026-10-13T02:11:15.184773Z",
     "shell.execute_reply": "2026-10-13T02:11:15.184578Z"
    }
   },
   "outputs": [],
   "source": [
    "known = {0:0, 1:1}\n",
    "\n",
    "def fibonacci_memo(n):\n",
    "    if n in known:\n",
    "        return known[n]\n",
    "\n",
    "    res = fibonacci_memo(n-1) + fibonacci_memo(n-2)\n",
    "    known[n] = res\n",
    "    return res"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e0f99099",
   "metadata": {},
   "source": [
    "`known` starts with the two base cases. Each call either retrieves a cached result or computes and stores a new one. The call graph shows why caching helps: the plain recursive version repeats the same subproblems.\n",
    "\n",
    "Reset `known` before timing a first computation. A second call measures retrieval from the cache, which is a different operation. Use a small input for the plain recursive function so the demonstration stays quick."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 72,
   "id": "1c07b053",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:15.186554Z",
     "iopub.status.busy": "2026-10-13T02:11:15.186371Z",
     "iopub.status.idle": "2026-10-13T02:11:15.192555Z",
     "shell.execute_reply": "2026-10-13T02:11:15.192323Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Plain result: 6765\n",
      "Plain seconds: 0.0013913750881329179\n",
      "First memoized seconds: 4.041939973831177e-06\n",
      "Cached seconds: 3.3294782042503357e-07\n",
      "Memoized result: 6765\n"
     ]
    }
   ],
   "source": [
    "from timeit import timeit\n",
    "\n",
    "print('Plain result:', fibonacci(20))\n",
    "print('Plain seconds:', timeit(lambda: fibonacci(20), number=1))\n",
    "known = {0: 0, 1: 1}\n",
    "print('First memoized seconds:', timeit(lambda: fibonacci_memo(20), number=1))\n",
    "print('Cached seconds:', timeit(lambda: fibonacci_memo(20), number=1))\n",
    "print('Memoized result:', fibonacci_memo(20))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 73,
   "id": "ch07-memo-ex",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:15.193460Z",
     "iopub.status.busy": "2026-10-13T02:11:15.193387Z",
     "iopub.status.idle": "2026-10-13T02:11:15.194760Z",
     "shell.execute_reply": "2026-10-13T02:11:15.194582Z"
    },
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Memoize a Function\n",
    "#   The Lucas numbers start with lucas(0) = 2 and lucas(1) = 1, and each later\n",
    "#   number is the sum of the two numbers before it.\n",
    "#   1. Create a dictionary `lucas_known` that maps 0 to 2 and 1 to 1.\n",
    "#   2. Write `lucas_memo(n)`. If n is a key in lucas_known, return the stored value.\n",
    "#      Otherwise compute lucas_memo(n-1) + lucas_memo(n-2), store the result in\n",
    "#      lucas_known, and return it.\n",
    "#   3. Print lucas_memo(30) and the number of items in lucas_known.\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 74,
   "id": "ch07-memo-sol",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-13T02:11:15.195596Z",
     "iopub.status.busy": "2026-10-13T02:11:15.195535Z",
     "iopub.status.idle": "2026-10-13T02:11:15.197158Z",
     "shell.execute_reply": "2026-10-13T02:11:15.196979Z"
    },
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1860498\n",
      "31\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "lucas_known = {0: 2, 1: 1}\n",
    "\n",
    "def lucas_memo(n):\n",
    "    if n in lucas_known:\n",
    "        return lucas_known[n]\n",
    "\n",
    "    res = lucas_memo(n-1) + lucas_memo(n-2)\n",
    "    lucas_known[n] = res\n",
    "    return res\n",
    "\n",
    "print(lucas_memo(30))      # 1860498\n",
    "print(len(lucas_known))    # 31: one memo for each n from 0 to 30"
   ]
  }
 ],
 "metadata": {
  "celltoolbar": "Tags",
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.16"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
