{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "53f15908",
   "metadata": {},
   "source": [
    "# Core Operations"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c0a1cc10",
   "metadata": {
    "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": "253c1a59",
   "metadata": {},
   "source": [
    "Common dictionary operations involve the following methods. \n",
    "\n",
    "| Group | Method | Description |\n",
    "|---|---|---|\n",
    "| **Reading** | `d.get(key, default)` | Return the value or a fallback without inserting |\n",
    "| | `d.keys()` | All keys |\n",
    "| | `d.values()` | All values |\n",
    "| | `d.items()` | All key-value pairs |\n",
    "| **Adding/Updating** | `d.update({...})` | Add or overwrite from another dict |\n",
    "| | `d.setdefault(key, default)` | Set value only if key doesn't exist |\n",
    "| **Removing** | `d.pop(key, default)` | Remove & return a specific key |\n",
    "| | `d.popitem()` | Remove & return last inserted pair |\n",
    "| | `d.clear()` | Remove everything |\n",
    "| **Copying/Creating** | `d.copy()` | Shallow copy |\n",
    "| | `dict.fromkeys(keys, value)` | Create new dict from a list of keys |\n",
    "| **Checking** | `'key' in d` | Check if key exists |\n",
    "| | `len(d)` | Count of key-value pairs |\n",
    "\n",
    "Lists identify elements by their positions; dictionaries identify values by their keys. The following table compares the core operations for both types.\n",
    "\n",
    "| Operation | List `nums` | Dictionary `d` |\n",
    "| --- | --- | --- |\n",
    "| Read one value | `nums[i]` uses an integer index. | `d[key]` uses a key. |\n",
    "| Read with a fallback | No equivalent to dictionary `get()`. | `d.get(key, default)` returns the default if the key is missing. |\n",
    "| Replace one value | `nums[i] = value` requires an existing index. | `d[key] = value` replaces an existing value or adds a new entry. |\n",
    "| Add an item | `nums.append(value)` adds to the end; `nums.insert(i, value)` adds at a position. | `d[key] = value` adds an entry if the key is new. |\n",
    "| Delete without returning a value | `del nums[i]` removes an element; `del nums[i:j]` removes a slice. | `del d[key]` removes an entry. |\n",
    "| Remove by value | `nums.remove(value)` removes the first matching element and returns `None`; it raises `ValueError` if no match exists. | No `remove()` method; delete an entry by its key using `del` or `pop()`. |\n",
    "| Remove and return one value | `nums.pop(i)` removes by index; no default-value argument is available. | `d.pop(key, default)` removes by key; the optional default handles a missing key. |\n",
    "| Remove the last item | `nums.pop()` returns the last element. | `d.popitem()` returns the last inserted `(key, value)` pair. |\n",
    "| Remove everything | `nums.clear()` | `d.clear()` |\n",
    "| Test membership | `value in nums` checks elements. | `key in d` checks keys; `value in d.values()` checks values. |\n",
    "| Iterate | `for value in nums` yields elements. | `for key in d` yields keys; `for key, value in d.items()` yields pairs. |\n",
    "| Count items | `len(nums)` counts elements. | `len(d)` counts key-value pairs. |\n",
    "\n",
    "For an invalid lookup or removal without a fallback, a list raises `IndexError` for an out-of-range index, while a dictionary raises `KeyError` for a missing key.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "84529af7",
   "metadata": {},
   "source": [
    "```{contents}\n",
    ":local:\n",
    ":depth: 2\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "278901e5",
   "metadata": {},
   "source": [
    "## Accessing Items\n",
    "\n",
    "Use `d[key]` to retrieve the value associated with a key. If the key is absent, a regular dictionary raises `KeyError`. Whether that is a problem depends on the data contract: which fields must be present, and which may be absent.\n",
    "\n",
    "- **Required field:** use `d[key]` when missing data should reveal an error that needs attention.\n",
    "- **Optional field:** use `d.get(key, default)` when absence is expected and the fallback has a meaningful interpretation.\n",
    "- **Create on first use:** use `setdefault()` when a missing entry should be inserted before you work with it.\n",
    "\n",
    "A fallback is a design choice. Replacing a missing required grade with zero could produce a misleading average; reporting a missing optional phone number as `\"N/A\"` can be appropriate.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f69e6d78",
   "metadata": {},
   "source": [
    "```{index} dict.get(), dict.keys(), dict.values(), dict.items()\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "8df66a13",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Alice\n",
      "{'name': 'Alice', 'age': 28, 'city': 'Rolla'}\n"
     ]
    }
   ],
   "source": [
    "person = {\n",
    "    \"name\": \"Alice\",\n",
    "    \"age\": 28,\n",
    "    \"city\": \"Rolla\"\n",
    "}\n",
    "\n",
    "# Access an item\n",
    "print(person[\"name\"])      # Alice\n",
    "print(person)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "966d157c",
   "metadata": {},
   "source": [
    "`KeyError` when trying to access a nonexistent key. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a572dad5",
   "metadata": {},
   "outputs": [],
   "source": [
    "%%expect KeyError\n",
    "print(person[\"phone\"])      # KeyError\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ee517266",
   "metadata": {},
   "source": [
    "`get()` returns a fallback only when the key is absent. With no explicit fallback, it returns `None`. It does not insert the fallback into the dictionary, and it does not replace an existing value, even when that value is `None`.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "66f12238",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "None\n",
      "N/A\n"
     ]
    }
   ],
   "source": [
    "print(person.get(\"phone\"))          # None\n",
    "print(person.get(\"phone\", \"N/A\"))   # N/A"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d7d4019d",
   "metadata": {},
   "source": [
    "### Choose What Absence Means\n",
    "\n",
    "```{index} missing dictionary keys, dict.setdefault()\n",
    "```\n",
    "\n",
    "Compare these operations using the same missing key. The printed dictionary after each operation shows whether the lookup changes the data. `setdefault()` returns the existing value when the key is already present; it does not overwrite it.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0853d00b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Before: {'name': 'Ana'}\n",
      "Required phone is missing\n",
      "After brackets: {'name': 'Ana'}\n",
      "Optional phone: N/A\n",
      "After get: {'name': 'Ana'}\n",
      "Created phone: N/A\n",
      "After setdefault: {'name': 'Ana', 'phone': 'N/A'}\n",
      "Existing phone: N/A\n"
     ]
    }
   ],
   "source": [
    "record = {'name': 'Ana'}\n",
    "print('Before:', record)\n",
    "try:\n",
    "    print(record['phone'])  # Required lookup: intentionally demonstrate KeyError.\n",
    "except KeyError:\n",
    "    print('Required phone is missing')\n",
    "print('After brackets:', record)\n",
    "\n",
    "print('Optional phone:', record.get('phone', 'N/A'))\n",
    "print('After get:', record)\n",
    "\n",
    "print('Created phone:', record.setdefault('phone', 'N/A'))\n",
    "print('After setdefault:', record)\n",
    "print('Existing phone:', record.setdefault('phone', 'unknown'))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5002c7f3",
   "metadata": {},
   "source": [
    "In Section 7.3, `defaultdict(list)` extends the create-on-first-use pattern for grouping: bracket access creates a missing list, but `.get()` does not invoke the factory. Use it when creating groups is intended, rather than merely checking whether a group exists.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "22f85a93",
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = {'zero': 0, 'one': 1, 'two': 2}\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bfe9aba3",
   "metadata": {},
   "source": [
    "To access all the keys and values at once:\n",
    "\n",
    "- `keys()` returns a view of all the dictionary's  keys\n",
    "- `values()` returns a view of all the dictionary's values.\n",
    "- `items()` returns a view of all key-value pairs as tuples."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "e841ea8c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "zero one two \n",
      "0 1 2 \n",
      "zero 0 one 1 two 2 "
     ]
    }
   ],
   "source": [
    "for k in numbers.keys():\n",
    "    print(k, end=' ')\n",
    "print()\n",
    "\n",
    "for v in numbers.values():\n",
    "    print(v, end=' ')\n",
    "print()\n",
    "\n",
    "for k, v in numbers.items():\n",
    "    print(k, v , end=' ')\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2a027a6b",
   "metadata": {},
   "source": [
    "The `len` function works on dictionaries; it returns the number of items."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "1b4ea0c2",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(numbers)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "75edaa2a",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Accessing Dictionary Values\n",
    "# Given the dictionary below:\n",
    "# 1. Print the value associated with \"name\".\n",
    "# 2. Use .get() to retrieve \"email\" with a default of \"N/A\".\n",
    "# 3. Print all keys and values using .items().\n",
    "person = {\"name\": \"Bob\", \"age\": 25, \"city\": \"Chicago\"}\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "1c7bf62e",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Bob\n",
      "N/A\n",
      "name Bob\n",
      "age 25\n",
      "city Chicago\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "person = {\"name\": \"Bob\", \"age\": 25, \"city\": \"Chicago\"}\n",
    "\n",
    "# 1. Access \"name\"\n",
    "print(person[\"name\"])\n",
    "\n",
    "# 2. Get \"email\" safely with a default\n",
    "print(person.get(\"email\", \"N/A\"))\n",
    "\n",
    "# 3. Iterate with .items()\n",
    "for key, value in person.items():\n",
    "    print(key, value)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "53355982",
   "metadata": {},
   "source": [
    "## Adding/Updating Items"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9456379e",
   "metadata": {},
   "source": [
    "```{index} dict.update(), dict.setdefault()\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "767dd9a6",
   "metadata": {},
   "source": [
    "You also use the square brackets to update values. An item assignment like `person[\"age\"] = 30` will either \n",
    "  - updates an existing item, or \n",
    "  - creates a new item if the key does not already exist. \n",
    "\n",
    "Dictionary keys must remain hashable, with stable hashes and equality behavior while stored. Assigning to `person[\"age\"]` changes the associated value, not the key. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "1364437e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'name': 'Bob', 'age': 29, 'city': 'Chicago', 'email': 'alice@rolla.com'}\n"
     ]
    }
   ],
   "source": [
    "# Modify an existing item\n",
    "person[\"age\"] = 29\n",
    "\n",
    "# Add a new item\n",
    "person[\"email\"] = \"alice@rolla.com\"\n",
    "\n",
    "print(person)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6c98292a",
   "metadata": {},
   "source": [
    "`d.update()` is used to add new key-value pairs or change existing ones in a dictionary. `d.update()` behaves like above but can work with multiple key-value pairs:\n",
    "\n",
    "- if the key already exists, its value is replaced\n",
    "- if the key does not exist, it is added"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "ee77f927",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'a': 1, 'b': 20, 'c': 3}\n"
     ]
    }
   ],
   "source": [
    "d = {\"a\": 1, \"b\": 2}\n",
    "d.update({\"b\": 20, \"c\": 3})\n",
    "\n",
    "print(d)   # {'a': 1, 'b': 20, 'c': 3}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9878c801",
   "metadata": {},
   "source": [
    "An alternative syntax for `d.update()` is as follows."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "53c15a08",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'a': 10, 'b': 20, 'c': 3, 'd': 4}\n"
     ]
    }
   ],
   "source": [
    "d.update(a=10, d=4)\n",
    "print(d)   # {'a': 10, 'b': 20, 'c': 3, 'd': 4}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "73968a37",
   "metadata": {},
   "source": [
    "To rename a dictionary entry, replace its key rather than changing the existing key object. You can:\n",
    "\n",
    "1. Add a new key\n",
    "2. Copy the value\n",
    "3. Delete the old key\n",
    "\n",
    "The following assignment uses `pop()` to remove the old entry and return its value, then stores that value under the new key."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "c60b6dac",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'name': 'Doris', 'years': 29}\n"
     ]
    }
   ],
   "source": [
    "student = {\n",
    "    \"name\": \"Doris\",\n",
    "    \"age\": 29\n",
    "}\n",
    "\n",
    "# Rename key \"age\" to \"years\"\n",
    "student[\"years\"] = student.pop(\"age\")\n",
    "\n",
    "print(student)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "a48929a3",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Adding and Updating Dictionary Items\n",
    "# Start with this dictionary:\n",
    "# 1. Add a new key \"email\" with value \"alice@example.com\".\n",
    "# 2. Update \"age\" to 30.\n",
    "# 3. Use d.update() to add \"city\": \"Boston\" and change \"name\" to \"Alicia\".\n",
    "# 4. Print the final dictionary.\n",
    "person = {\"name\": \"Alice\", \"age\": 28}\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "39ca8124",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'name': 'Alicia', 'age': 30, 'email': 'alice@example.com', 'city': 'Boston'}\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "person = {\"name\": \"Alice\", \"age\": 28}\n",
    "\n",
    "# 1. Add \"email\"\n",
    "person[\"email\"] = \"alice@example.com\"\n",
    "\n",
    "# 2. Update \"age\"\n",
    "person[\"age\"] = 30\n",
    "\n",
    "# 3. Use update()\n",
    "person.update({\"city\": \"Boston\", \"name\": \"Alicia\"})\n",
    "\n",
    "# 4. Print\n",
    "print(person)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b7d350b0",
   "metadata": {},
   "source": [
    "## Deleting Items\n",
    "\n",
    "You can remove a key-value pair when you no longer need it:\n",
    "\n",
    "- `del d[key]` removes the item with the given key.\n",
    "- `d.pop(key)` removes the item with the given key and returns its value.\n",
    "- `d.popitem()` removes the last inserted item and returns it as a `(key, value)` tuple.\n",
    "- `d.clear()` removes all items.\n",
    "\n",
    "`del` is a Python keyword used in a statement, rather than a method call. It deletes the target you specify: `del d[key]` removes a dictionary entry, `del nums[0]` removes a list element, and `del nums[1:3]` removes a list slice. You can also use `del name` to remove a variable binding; this does not necessarily destroy the object, because other variables may still refer to it. Unlike `pop()`, `del` does not return the removed value.\n",
    "\n",
    "Both `del d[key]` and `d.pop(key)` raise `KeyError` if the key is missing. To handle a missing key without an error, use `d.pop(key, default)`. It returns the default value and leaves the dictionary unchanged; it does not insert the default.\n",
    "\n",
    "Unlike dictionary `pop()`, which requires a key, list `pop(index)` takes an optional index and has no default-value argument. List `pop()` with no argument is closer to dictionary `popitem()`: both remove the last item, but the list returns an element and the dictionary returns a key-value pair.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0ae07078",
   "metadata": {},
   "source": [
    "```{index} dict.pop(), dict.clear(), del statement\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "2d66454f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "person:\t\t {'name': 'Alice', 'age': 29, 'city': 'Rolla', 'email': 'alice@rolla.com'}\n",
      "city deleted:\t {'name': 'Alice', 'age': 29, 'email': 'alice@rolla.com'}\n",
      "x_city_email:\t {'name': 'Alice', 'age': 29}\n",
      "email_popped:\t alice@rolla.com\n",
      "person_updated\t {'name': 'Alice', 'age': 29}\n",
      "popped_k_v:\t ('age', 29)\n",
      "after_popitem:\t {'name': 'Alice'}\n",
      "after_clear:\t {}\n"
     ]
    }
   ],
   "source": [
    "person = {\n",
    "    \"name\": \"Alice\",\n",
    "    \"age\": 29,\n",
    "    \"city\": \"Rolla\",\n",
    "    \"email\": \"alice@rolla.com\"\n",
    "}\n",
    "print(\"person:\\t\\t\", person)\n",
    "\n",
    "# Delete an item using del\n",
    "del person[\"city\"]                          # in place\n",
    "print(\"city deleted:\\t\", person)\n",
    "\n",
    "# Delete an item using pop()\n",
    "email_popped = person.pop(\"email\")\n",
    "\n",
    "print(\"x_city_email:\\t\", person)            # {'name': 'Alice', 'age': 29}\n",
    "print(\"email_popped:\\t\", email_popped)      # alice@rolla.com\n",
    "\n",
    "print(\"person_updated\\t\", person)\n",
    "\n",
    "# Delete the last added item using popitem() \n",
    "key, value = person.popitem()\n",
    "print(\"popped_k_v:\\t\", (key, value))        # ('age', 29) \n",
    "print(\"after_popitem:\\t\", person)           # {'name': 'Alice'}\n",
    "\n",
    "# Clear all items from the dictionary\n",
    "person.clear()\n",
    "print(\"after_clear:\\t\", person)  # {}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d15ec8b2",
   "metadata": {},
   "outputs": [],
   "source": [
    "person = {\"name\": \"Alice\", \"city\": \"Rolla\"}\n",
    "\n",
    "print(person.pop(\"city\", \"N/A\"))   # Rolla: the key exists\n",
    "print(person.pop(\"phone\", \"N/A\"))  # N/A: the key is missing\n",
    "print(person)                      # {'name': 'Alice'}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "421def9d",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Deleting Dictionary Items\n",
    "# Start with this dictionary:\n",
    "# 1. Delete \"city\" using del.\n",
    "# 2. Remove and capture \"email\" using pop(). Print the popped value.\n",
    "# 3. Print the remaining dictionary.\n",
    "person = {\"name\": \"Bob\", \"age\": 25, \"city\": \"Boston\", \"email\": \"bob@email.com\"}\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "1954cc0b",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Popped email: bob@email.com\n",
      "{'name': 'Bob', 'age': 25}\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "person = {\"name\": \"Bob\", \"age\": 25, \"city\": \"Boston\", \"email\": \"bob@email.com\"}\n",
    "\n",
    "# 1. Delete \"city\"\n",
    "del person[\"city\"]\n",
    "\n",
    "# 2. Pop \"email\"\n",
    "email_val = person.pop(\"email\")\n",
    "print(\"Popped email:\", email_val)\n",
    "\n",
    "# 3. Print remaining\n",
    "print(person)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4bafae76",
   "metadata": {},
   "source": [
    "## Membership Testing\n",
    "\n",
    "The `in` membership operator works on dictionaries, too; it tells you whether a **key** exists in the dictionary, which returns `True` if the key is present and `False` if it is not. You can also use `not in` to check that a key is missing. \n",
    "\n",
    "Member testing is useful when you want to safely decide whether to access, update, or delete a dictionary item.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "93b10f65",
   "metadata": {},
   "source": [
    "```{index} membership testing; dict\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "a50e687e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n",
      "False\n",
      "True\n",
      "Age exists: 29\n"
     ]
    }
   ],
   "source": [
    "person = {\n",
    "    \"name\": \"Alice\",\n",
    "    \"age\": 29,\n",
    "    \"city\": \"Rolla\"\n",
    "}\n",
    "\n",
    "print(\"name\" in person)        # True\n",
    "print(\"email\" in person)       # False\n",
    "print(\"email\" not in person)   # True\n",
    "\n",
    "if \"age\" in person:             # safety: Check if key exists before accessing\n",
    "    print(\"Age exists:\", person[\"age\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "91cba20b",
   "metadata": {},
   "source": [
    "The `in` operator does *not* check whether something appears as a value."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "79ff562e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"Alice\" in person"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "93e478fe",
   "metadata": {},
   "source": [
    "To see whether something appears as a **value** in a dictionary, you can use the method `values`, which returns a sequence of values, and then use the `in` operator."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "5b24c03a",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 28,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"Alice\" in person.values()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "f77a0477",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Membership Testing\n",
    "# Use the dictionary below:\n",
    "# 1. Check if \"name\" is in the dictionary and print the result.\n",
    "# 2. Check if \"phone\" is NOT in the dictionary and print the result.\n",
    "# 3. Check if \"Alice\" appears as a value and print the result.\n",
    "person = {\"name\": \"Alice\", \"age\": 29, \"city\": \"Rolla\"}\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "id": "1dc0509f",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n",
      "True\n",
      "True\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "person = {\"name\": \"Alice\", \"age\": 29, \"city\": \"Rolla\"}\n",
    "\n",
    "# 1. \"name\" in person\n",
    "print(\"name\" in person)              # True\n",
    "\n",
    "# 2. \"phone\" not in person\n",
    "print(\"phone\" not in person)         # True\n",
    "\n",
    "# 3. \"Alice\" in values\n",
    "print(\"Alice\" in person.values())    # True"
   ]
  }
 ],
 "metadata": {
  "celltoolbar": "Tags",
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "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.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
