{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "737e79eb",
   "metadata": {},
   "source": [
    "# Dictionaries"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "200584f6",
   "metadata": {
    "tags": [
     "hide-input",
     "thebe-init"
    ]
   },
   "outputs": [],
   "source": [
    "import sys\n",
    "from pathlib import Path\n",
    "\n",
    "current = Path.cwd()\n",
    "for parent in [current, *current.parents]:\n",
    "    if (parent / '_config.yml').exists():\n",
    "        project_root = parent  # ← Add project root, not chapters\n",
    "        break\n",
    "else:\n",
    "    project_root = Path.cwd().parent.parent\n",
    "\n",
    "sys.path.insert(0, str(project_root))\n",
    "\n",
    "from shared import thinkpython, diagram, jupyturtle\n",
    "from shared.download import download\n",
    "\n",
    "# Register as top-level modules so direct imports work in subsequent cells\n",
    "sys.modules['thinkpython'] = thinkpython\n",
    "sys.modules['diagram'] = diagram\n",
    "sys.modules['jupyturtle'] = jupyturtle\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9963a57e",
   "metadata": {},
   "source": [
    "This chapter presents a built-in type called a dictionary.\n",
    "\n",
    "It is one of Python's best features -- and the building block of many efficient and elegant algorithms.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8ce99c2d",
   "metadata": {},
   "source": [
    "```{contents}\n",
    ":local:\n",
    ":depth: 2\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "be7467bb",
   "metadata": {},
   "source": [
    "## What Is a Dictionary?\n",
    "\n",
    "A dictionary in Python is a built-in data type used to store data in key–value pairs. A Python dictionary is like a real world dictionary, where you look up a word for its definition. In Python dictionary, you look up a **key** for the **value**. \n",
    "\n",
    "The key characteristics of a dictionary are:\n",
    "\n",
    "1. Dictionaries are **mutable** (can be changed)\n",
    "2. Keys must be **hashable** (strings and numbers; tuples only when every element is hashable)\n",
    "3. A dictionary represents a **mapping** from **keys** to **values**. \n",
    "4. **Keys** must be **unique**\n",
    "5. **Values** can be any data type\n",
    "\n",
    "**Hashable** means an object has a hash value that remains stable during its lifetime, and equal objects have equal hashes. Python uses these properties to locate dictionary keys. Strings and numbers are hashable; lists, dictionaries, and sets are not. A tuple such as `(1, \"apple\")` is hashable, but `(1, [\"apple\"])` is not because it contains a list.\n",
    "\n",
    "Hashability is not the same as immutability. A tuple is immutable but can contain an unhashable element. Some user-defined objects are mutable yet hashable by identity; you will meet those objects in the object-oriented programming chapter. For now, choose keys from the familiar hashable types above.\n",
    "\n",
    "See Python's [definition of hashable](https://docs.python.org/3/glossary.html#term-hashable).\n",
    "\n",
    "In terms of formatting, \n",
    "- Each dictionary item consists of a **key** and a **value** separated by a **colon**. \n",
    "- Dictionary items are separated by **commas** and enclosed in **curly braces**."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3f5164b9",
   "metadata": {},
   "source": [
    "```{index} dictionary, key, value, key-value pair, mapping\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3a94f8ae",
   "metadata": {},
   "source": [
    "A **dictionary** is like a list, but more general. In a list, the indices have to be integers; in a dictionary they can be (almost) any type.\n",
    "\n",
    "| Feature   | List             | Dictionary        |\n",
    "| --------- | ---------------- | ----------------- |\n",
    "| Access by | Index (0,1,2)    | Key               |\n",
    "| Structure | Ordered sequence | Key-value mapping |\n",
    "| Best for  | Ordered data     | Labeled data      |\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bb0fdc15",
   "metadata": {},
   "source": [
    "As seen in the example below: \n",
    "\n",
    "- A **list** of number words can be accessed using an integer as an **index**. \n",
    "- A **dictionary** goes in the other direction, and look up a word to get the corresponding integer; in other words, using the keys to look up the values."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "20dd9f32",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['zero', 'one', 'two']\n",
      "one\n",
      "{'zero': 0, 'one': 1, 'two': 2}\n",
      "1\n"
     ]
    }
   ],
   "source": [
    "nums_lst = ['zero', 'one', 'two']\n",
    "print(nums_lst)\n",
    "print(nums_lst[1])\n",
    "\n",
    "nums_dic = {'zero': 0, 'one': 1, 'two': 2}\n",
    "print(nums_dic)\n",
    "print(nums_dic['one'])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2c2f6f79",
   "metadata": {},
   "source": [
    "In mathematical language, a dictionary represents a **mapping** from keys to values, so you can also say that each key \"maps to\" a value.\n",
    "In this example, each number word maps to the corresponding integer.\n",
    "\n",
    "The following figure shows the state diagram for `numbers`.\n",
    "A dictionary is represented by a box with the word \"dict\" outside and the items inside.\n",
    "Each item is represented by a key and an arrow pointing to a value.\n",
    "The quotation marks indicate that the keys here are strings, not variable names."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "e9004edf",
   "metadata": {
    "tags": [
     "remove-input"
    ]
   },
   "outputs": [],
   "source": [
    "from shared.diagram import make_dict, Binding, Value\n",
    "\n",
    "numbers = {'zero': 0, 'one': 1, 'two': 2}\n",
    "\n",
    "d1 = make_dict(numbers, dy=-0.3, offsetx=0.37)\n",
    "binding1 = Binding(Value('numbers'), d1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "3b05ed1f",
   "metadata": {
    "tags": [
     "remove-input"
    ]
   },
   "outputs": [
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAMsAAACQCAYAAACmsp8HAAAAOnRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjEwLjcsIGh0dHBzOi8vbWF0cGxvdGxpYi5vcmcvTLEjVAAAAAlwSFlzAAAPYQAAD2EBqD+naQAACz5JREFUeJzt3QVoVX0YBvB3zsLC7g5snd3xqSioOJNNVCwEGSbqZCbYmCjqsBWdYmEiGOjsbuyuWdiBdd3H88K9bOq2V73bDZ8fDHfv7u499+w85/8/m+c5AbGxsbFCRElKlfRDiIhhIfoNHFmIjBgWIiOGhciIYSEyYliIjBgWIiOGhciIYSEyYliIjBgWIiOGhciIYSEyYliIjBgWIiOGhci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qTk89IW/blz5+rFmbZs2SJZs2ZNluVhWPxA37599bc/2Jtivo5jF4QBrfLFihXTx+AiR7gfwYCePXvqxY1wxS9A435YWJh4C4fDob/+xbQrqWOVR48eyYgRI6Ro0aJ66T/ApTMwkroTW/Q9jC36nscWfSI34wE+kRHDQmTEsBAZMSxERgwLkRHDQmTEsBAZMSxERgwLkRHDQmTE/xtGZMSRhciIYSEyYliIjBgWIiOGhciIYSEyYliIjBgWIiOGhciIYSEyYliIjBgWIiOGhciIYSEyYliIjBgWIiOGhciIYSEyYliIxOZ/T4d3FbPW4PEAAAAASUVORK5CYII=",
      "text/plain": [
       "<Figure size 183x124 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from shared.diagram import diagram, adjust, Bbox\n",
    "\n",
    "width, height, x, y = [1.83, 1.24, 0.49, 0.85]\n",
    "ax = diagram(width, height)\n",
    "bbox = binding1.draw(ax, x, y)\n",
    "# adjust(x, y, bbox)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "38e53b79",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Read a Dictionary Diagram *(basic)*\n",
    "# The dictionary below maps course codes to course titles.\n",
    "# 1. Print the title for \"DS210\".\n",
    "# 2. Look up the title for \"STAT301\", store it in a variable named stat_title,\n",
    "#    and print it.\n",
    "# 3. Use an f-string and a lookup to print the line:\n",
    "#    CS101: Introduction to Programming\n",
    "courses = {\n",
    "    \"CS101\": \"Introduction to Programming\",\n",
    "    \"DS210\": \"Data Management\",\n",
    "    \"STAT301\": \"Applied Statistics\",\n",
    "}\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "a679bfe1",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Data Management\n",
      "Applied Statistics\n",
      "CS101: Introduction to Programming\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "courses = {\n",
    "    \"CS101\": \"Introduction to Programming\",\n",
    "    \"DS210\": \"Data Management\",\n",
    "    \"STAT301\": \"Applied Statistics\",\n",
    "}\n",
    "\n",
    "print(courses[\"DS210\"])\n",
    "stat_title = courses[\"STAT301\"]\n",
    "print(stat_title)\n",
    "print(f\"CS101: {courses['CS101']}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fc778385",
   "metadata": {},
   "source": [
    "## When to Use a Dictionary\n",
    "\n",
    "You use a dictionary when:\n",
    "- You need labeled data\n",
    "- You want fast lookups by name\n",
    "- You need a mapping relationship\n",
    "\n",
    "Examples of dictionaries:\n",
    "\n",
    "- Student records\n",
    "- **Configuration** settings\n",
    "- Word counts\n",
    "- **JSON** data"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-fc778385",
   "metadata": {},
   "source": [
    "```{index} dictionary, mapping\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "s2b-dict-zip-md",
   "metadata": {},
   "source": [
    "Data often arrives as two parallel lists, one holding the keys and one holding the values. The `zip()` function from Chapter 6 pairs them up position by position, and `dict()` turns those `(key, value)` pairs into a dictionary:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "s2b-dict-zip-code",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'apple': 1.25, 'banana': 0.5, 'cherry': 3.0}\n",
      "0.5\n"
     ]
    }
   ],
   "source": [
    "fruits = [\"apple\", \"banana\", \"cherry\"]\n",
    "prices = [1.25, 0.50, 3.00]\n",
    "\n",
    "price_of = dict(zip(fruits, prices))\n",
    "print(price_of)\n",
    "print(price_of[\"banana\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f5cbf379",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Choose a Mapping *(applied)*\n",
    "# A small app stores student grades. Use a dictionary when each student name\n",
    "# should map directly to one numeric grade.\n",
    "# 1. Build a dictionary named gradebook from names and grades.\n",
    "# 2. Print Chloe's grade.\n",
    "# 3. Print the full gradebook.\n",
    "names = [\"Ava\", \"Ben\", \"Chloe\"]\n",
    "grades = [94, 87, 91]\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a4dcb05a",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "91\n",
      "{'Ava': 94, 'Ben': 87, 'Chloe': 91}\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "names = [\"Ava\", \"Ben\", \"Chloe\"]\n",
    "grades = [94, 87, 91]\n",
    "\n",
    "gradebook = dict(zip(names, grades))\n",
    "print(gradebook[\"Chloe\"])\n",
    "print(gradebook)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6ef15bbc",
   "metadata": {},
   "source": [
    "## Creating Dictionaries\n",
    "\n",
    "Python provides several ways to create a dictionary, depending on whether you already have the data or are building it incrementally.\n",
    "\n",
    "1. **dict literal**: the most common approach to create a dictionary\n",
    "2. `dict()` constructor: to turn sequences into dictionaries\n",
    "3. dictionary comprehensions: are useful when keys and values come from other sources"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c6576618",
   "metadata": {},
   "source": [
    "```{index} dict() constructor, dictionary literal, dict comprehension\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "657c28ae",
   "metadata": {},
   "source": [
    "Python also has a `dict.fromkeys()` method, which is a special case in creating dictionaries. Overall, common ways to create a dictionary include:\n",
    "\n",
    "| # | Method | Syntax | Notes |\n",
    "|---|---|---|---|\n",
    "| 1 | Empty dict literal | `{}` | Fastest way to create an empty dict |\n",
    "| 2 | Dict literal | `{'a': 1, 'b': 2}` | Keys and values known up front |\n",
    "| 3 | `dict()` constructor | `dict(a=1, b=2)` | Keys must be valid identifiers |\n",
    "| 4 | From list of tuples | `dict([('a', 1), ('b', 2)])` | Useful when pairs are already in a sequence |\n",
    "| 5 | `dict.fromkeys()` | `dict.fromkeys(['a', 'b'], 0)` | All keys share the same default value |\n",
    "| 6 | Dict comprehension | `{k: v for k, v in items}` | Build from any iterable with an expression |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9e3f77f0",
   "metadata": {},
   "source": [
    "Pay attention to ways 2, 3, and 4. We usually use dict literal for creating dictionaries but you should know how to use the `dict()` constructor to turn a sequence into a dictionary. Also, try to transfer your skill in list comprehensions to dictionary comprehensions. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "fe26184b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Empty literal:        {}\n",
      "Dict literal:         {'zero': 0, 'one': 1, 'two': 2}\n",
      "dict() keywords:      {'zero': 0, 'one': 1, 'two': 2}\n",
      "dict() from tuples:   {'zero': 0, 'one': 1, 'two': 2}\n",
      "dict.fromkeys():      {'zero': 0, 'one': 0, 'two': 0}\n",
      "Dict comprehension:   {'zero': 0, 'one': 1, 'two': 2}\n"
     ]
    }
   ],
   "source": [
    "# 1. Empty dict literal\n",
    "d1 = {}\n",
    "\n",
    "# 2. Dict literal with items\n",
    "d2 = {'zero': 0, 'one': 1, 'two': 2}\n",
    "\n",
    "# 3. dict() constructor with keyword arguments (keys must be valid identifiers)\n",
    "d3 = dict(zero=0, one=1, two=2)\n",
    "\n",
    "# 4. dict() from a list of (key, value) tuples\n",
    "d4 = dict([('zero', 0), ('one', 1), ('two', 2)])\n",
    "\n",
    "# 5. dict.fromkeys() — all keys share the same default value\n",
    "d5 = dict.fromkeys(['zero', 'one', 'two'], 0)\n",
    "\n",
    "# 6. Dict comprehension\n",
    "words = ['zero', 'one', 'two']\n",
    "d6 = {word: idx for idx, word in enumerate(words)} # note the two variables\n",
    "\n",
    "print(\"Empty literal:       \", d1)\n",
    "print(\"Dict literal:        \", d2)\n",
    "print(\"dict() keywords:     \", d3)\n",
    "print(\"dict() from tuples:  \", d4)\n",
    "print(\"dict.fromkeys():     \", d5)\n",
    "print(\"Dict comprehension:  \", d6)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e5909815",
   "metadata": {},
   "source": [
    "To give some details about dictionary creation, let's use the dictionary literal to create a dictionary, which is to put the items inside curly braces. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "d73e8aab",
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = {'zero': 0, 'one': 1, 'two': 2}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b79066d8",
   "metadata": {},
   "source": [
    "Each item consists of a **key** and a **value** separated by a **colon**.\n",
    "The items are separated by commas and enclosed in curly braces.\n",
    "\n",
    "Another way to create a dictionary is to use the `dict` function.\n",
    "We can make an empty dictionary like this."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "f597dc41",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{}"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "empty = dict()\n",
    "empty"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "991fb3e2",
   "metadata": {},
   "source": [
    "Or, if you have a list like [ \"zero\", \"one\", \"two\"], you can use `enumerate()` to create a dictionary."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "888528e3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'zero': 0, 'one': 1, 'two ': 2}\n"
     ]
    }
   ],
   "source": [
    "lst = [\"zero\", \"one\", \"two \"]\n",
    "\n",
    "dict_words = {}\n",
    "for idx, word in enumerate(lst):\n",
    "    dict_words[word] = idx\n",
    "\n",
    "print(dict_words)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ffa68b39",
   "metadata": {},
   "source": [
    "Assignment creates an alias, just as it does for lists in Chapter 6. `dict(original)` and `original.copy()` create a separate outer dictionary. Compare the effects of changing an entry through an alias and through a copy:\n",
    "\n",
    "```{index} dictionary aliasing, dictionary copy, shallow copy\n",
    "```\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dcca0d56",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Original: {'zero': 0, 'one': 10, 'two': 2}\n",
      "Alias: {'zero': 0, 'one': 10, 'two': 2}\n",
      "Copy: {'zero': 0, 'one': 1, 'two': 20}\n",
      "Alias is original: True\n",
      "Copy is original: False\n"
     ]
    }
   ],
   "source": [
    "numbers = {'zero': 0, 'one': 1, 'two': 2}\n",
    "alias = numbers\n",
    "numbers_copy = dict(numbers)  # numbers.copy() has the same copying behavior.\n",
    "alias['one'] = 10\n",
    "numbers_copy['two'] = 20\n",
    "print('Original:', numbers)\n",
    "print('Alias:', alias)\n",
    "print('Copy:', numbers_copy)\n",
    "print('Alias is original:', alias is numbers)\n",
    "print('Copy is original:', numbers_copy is numbers)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "166437bb",
   "metadata": {},
   "source": [
    "The alias refers to the original dictionary, so assigning through the alias changes the original. The copy has its own entries, so replacing an entry in the copy does not replace that entry in the original.\n",
    "\n",
    "Both `dict(original)` and `.copy()` make a **shallow copy**: they copy the outer dictionary but retain references to its values. Inner lists and dictionaries can still be shared. Section 7.3 demonstrates this with nested student grades and shows how to copy the inner container when independent changes are needed.\n",
    "\n",
    "`dict.fromkeys(keys, value)` also reuses one value object for every key. An immutable default such as zero works for independent numeric updates. A list default is shared, so use a comprehension such as `{name: [] for name in names}` when each key needs its own list. Section 7.3 demonstrates and repairs this shared-list behavior.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5e524358",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Create Dictionaries Three Ways *(basic)*\n",
    "# 1. Create a dict literal named capitals with Missouri -> Jefferson City\n",
    "#    and Kansas -> Topeka.\n",
    "# 2. Create a dictionary named status from the list pairs.\n",
    "# 3. Use a dictionary comprehension to map each word in words to its length.\n",
    "# 4. Print all three dictionaries.\n",
    "pairs = [(\"draft\", 3), (\"review\", 2), (\"done\", 5)]\n",
    "words = [\"data\", \"python\", \"mapping\"]\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d878957d",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'Missouri': 'Jefferson City', 'Kansas': 'Topeka'}\n",
      "{'draft': 3, 'review': 2, 'done': 5}\n",
      "{'data': 4, 'python': 6, 'mapping': 7}\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "capitals = {\"Missouri\": \"Jefferson City\", \"Kansas\": \"Topeka\"}\n",
    "pairs = [(\"draft\", 3), (\"review\", 2), (\"done\", 5)]\n",
    "status = dict(pairs)\n",
    "words = [\"data\", \"python\", \"mapping\"]\n",
    "lengths = {word: len(word) for word in words}\n",
    "\n",
    "print(capitals)\n",
    "print(status)\n",
    "print(lengths)\n"
   ]
  }
 ],
 "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.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
