{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Topic 5: Dictionaries, sets and comprehensions\n",
    "\n",
    "Asiman Data School, Module 1: Foundations of Python Programming. Week 3, Tuesday.\n",
    "\n",
    "This notebook follows the lesson page. Read the text, run the cell under it with Shift + Enter, then change the values in the cell and run it again. Seeing the output change is how the rules become clear.\n",
    "\n",
    "Run the cells from top to bottom. When a cell reads input, a small box appears: type the values there and press Enter. The practice problems are in a separate notebook, topic-05-practice.ipynb.\n",
    "\n",
    "Contents\n",
    "\n",
    "1. Dictionaries: creating and reading\n",
    "2. Adding, changing and removing\n",
    "3. Keys, values, rules for keys and copying\n",
    "4. Going through a dictionary with loops and if/else\n",
    "5. Nested data and building dictionaries\n",
    "6. Sets\n",
    "7. Set operations, loops with sets, and choosing a structure\n",
    "8. Comprehensions\n",
    "9. Common mistakes\n",
    "10. Solved problems (easy to medium-hard)\n",
    "11. Practice problems (try them yourself) (in topic-05-practice.ipynb)\n",
    "12. Check yourself (on the website)\n",
    "13. Quick summary"
   ],
   "id": "t05-000"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Introduction: dictionaries, sets and comprehensions\n",
    "\n",
    "What matters most in this lesson. Five things matter most today: creating a dictionary and reading it with `d[key]` and `d.get(key)`; adding and changing with `d[key] = value`; going through it with `for key, value in d.items()`; the counting pattern `counts[x] = counts.get(x, 0) + 1`; and a set for unique values and for comparing two groups.\n",
    "\n",
    "Comprehensions come at the end. Take them slowly: every comprehension in this lesson is also shown as a normal loop, and the loop is always a correct answer. There are 26 solved problems. You do not need all of them today: start with Level 1 and come back for the rest.\n",
    "\n",
    "A beginner-friendly guide to the next two data structures of Python, dictionaries and sets, and to comprehensions, the short way to build a list, a dictionary or a set in one line. It starts from the simplest examples and gets harder step by step. It shows every everyday dictionary operation (`get`, `update`, `pop`, `keys`, `values`, `items` and more), every set operation (union, intersection, difference and more), and how to use `if/else`, `for` and `while` with both. Then it walks through 26 solved problems from easy to medium-hard. At the end there are practice problems.\n",
    "\n",
    "You should already know variables, data types, operators, `if/else`, loops, functions, lists and tuples.\n",
    "\n",
    "## 1. Dictionaries: creating and reading\n",
    "\n",
    "### 1.1 What is a dictionary?\n",
    "\n",
    "Imagine you store the grades of three students in a list:"
   ],
   "id": "t05-001"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "grades = [85, 92, 78]\n",
    "print(grades[1])"
   ],
   "id": "t05-002"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Whose grade is `grades[1]`? You must remember that position 1 is Murad. With 500 students that is impossible. A dictionary stores each value together with a name for it, called a key:\n",
    "\n",
    "Change it and run: print the grade of `\"Leyla\"`."
   ],
   "id": "t05-003"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "grades = {\"Aylin\": 85, \"Murad\": 92, \"Leyla\": 78}\n",
    "print(grades[\"Murad\"])"
   ],
   "id": "t05-004"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Real-life picture: a real dictionary. You look up a word (the key) and get its meaning (the value). A phone book works the same way: name, then number.\n",
    "\n",
    "|  | List | Dictionary |\n",
    "| --- | --- | --- |\n",
    "| You find a value by | its position (index): `grades[1]` | its key: `grades[\"Murad\"]` |\n",
    "| Written with | `[ ]` | `{ }` with `key: value` pairs |\n",
    "\n",
    "### 1.2 Creating dictionaries\n",
    "\n",
    "A dictionary is written in curly brackets. Each item is a pair `key: value`, and the pairs are separated by commas:\n",
    "\n",
    "Change it and run: add a fourth pair to `student`, for example `\"email\"`."
   ],
   "id": "t05-005"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "student = {\"name\": \"Aylin\", \"age\": 20, \"city\": \"Baku\"}\n",
    "prices = {\"apple\": 1.5, \"bread\": 0.8, \"milk\": 2.0}\n",
    "empty = {}\n",
    "\n",
    "print(student)\n",
    "print(prices)\n",
    "print(empty)\n",
    "print(type(student))"
   ],
   "id": "t05-006"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- The keys are usually text or numbers. The values can be anything: numbers, text, lists, even other dictionaries.\n",
    "- A dictionary can be empty: `{}`.\n",
    "\n",
    "A long dictionary is easier to read with one pair per line:"
   ],
   "id": "t05-007"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "student = {\n",
    "    \"name\": \"Aylin\",\n",
    "    \"age\": 20,\n",
    "    \"city\": \"Baku\",\n",
    "}\n",
    "print(student)"
   ],
   "id": "t05-008"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.3 How many pairs? `len()`"
   ],
   "id": "t05-009"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "student = {\"name\": \"Aylin\", \"age\": 20, \"city\": \"Baku\"}\n",
    "print(len(student))\n",
    "print(len({}))"
   ],
   "id": "t05-010"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.4 Making a dictionary with `dict()`"
   ],
   "id": "t05-011"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "student = dict(name=\"Aylin\", age=20)\n",
    "print(student)\n",
    "\n",
    "pairs = [(\"apple\", 1.5), (\"bread\", 0.8)]\n",
    "prices = dict(pairs)\n",
    "print(prices)"
   ],
   "id": "t05-012"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`dict()` can build a dictionary from `name=value` arguments, or from a list of pairs (tuples with two items).\n",
    "\n",
    "### 1.5 Square brackets: `dictionary[key]`\n",
    "\n",
    "Change it and run: print `student[\"city\"]`."
   ],
   "id": "t05-013"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "student = {\"name\": \"Aylin\", \"age\": 20, \"city\": \"Baku\"}\n",
    "print(student[\"name\"])\n",
    "print(student[\"age\"])"
   ],
   "id": "t05-014"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A key that does not exist gives an error:\n",
    "\n",
    "```python\n",
    "student = {\"name\": \"Aylin\", \"age\": 20}\n",
    "print(student[\"email\"])\n",
    "```\n",
    "\n",
    "```\n",
    "KeyError: 'email'\n",
    "```\n",
    "\n",
    "A dictionary has no positions. `student[0]` does not mean \"the first item\": Python looks for a key that is the number 0.\n",
    "\n",
    "```python\n",
    "student = {\"name\": \"Aylin\", \"age\": 20}\n",
    "print(student[0])\n",
    "```\n",
    "\n",
    "```\n",
    "KeyError: 0\n",
    "```\n",
    "\n",
    "### 1.6 `get(key)`: reading without an error\n",
    "\n",
    "`get` gives the value if the key exists. If it does not, `get` gives `None` instead of an error:"
   ],
   "id": "t05-015"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "student = {\"name\": \"Aylin\", \"age\": 20}\n",
    "print(student.get(\"name\"))\n",
    "print(student.get(\"email\"))"
   ],
   "id": "t05-016"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can choose what `get` gives back for a missing key. This is called the default:\n",
    "\n",
    "Change it and run: ask for `\"city\"` with the default `\"unknown\"`."
   ],
   "id": "t05-017"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "student = {\"name\": \"Aylin\", \"age\": 20}\n",
    "print(student.get(\"email\", \"no email\"))\n",
    "print(student.get(\"age\", 0))"
   ],
   "id": "t05-018"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.7 Is the key there? `in` and `not in`\n",
    "\n",
    "`in` checks the keys, not the values:\n",
    "\n",
    "Change it and run: check `20 in student`. Is 20 a key?"
   ],
   "id": "t05-019"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "student = {\"name\": \"Aylin\", \"age\": 20}\n",
    "print(\"name\" in student)\n",
    "print(\"email\" in student)\n",
    "print(\"Aylin\" in student)\n",
    "print(\"email\" not in student)"
   ],
   "id": "t05-020"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`\"Aylin\" in student` is `False`, because `\"Aylin\"` is a value, not a key.\n",
    "\n",
    "| Way | Key exists | Key is missing |\n",
    "| --- | --- | --- |\n",
    "| `d[key]` | the value | `KeyError` |\n",
    "| `d.get(key)` | the value | `None` |\n",
    "| `d.get(key, default)` | the value | the default |\n",
    "| `key in d` | `True` | `False` |\n",
    "\n",
    "## 2. Adding, changing and removing\n",
    "\n",
    "### 2.1 Adding and changing\n",
    "\n",
    "Dictionaries are mutable (changeable), like lists.\n",
    "\n",
    "### 2.2 `dictionary[key] = value`\n",
    "\n",
    "The same line does two different jobs:\n",
    "\n",
    "- If the key exists, its value is changed.\n",
    "- If the key does not exist, a new pair is added.\n",
    "\n",
    "Change it and run: add a pair `\"email\"`, then change the name."
   ],
   "id": "t05-021"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "student = {\"name\": \"Aylin\", \"age\": 20}\n",
    "\n",
    "student[\"age\"] = 21             # the key exists: change\n",
    "student[\"city\"] = \"Baku\"        # the key is new: add\n",
    "print(student)"
   ],
   "id": "t05-022"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A very common pattern is to start with an empty dictionary and fill it:"
   ],
   "id": "t05-023"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "prices = {}\n",
    "prices[\"apple\"] = 1.5\n",
    "prices[\"bread\"] = 0.8\n",
    "print(prices)"
   ],
   "id": "t05-024"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Changing a number that is stored in a dictionary:\n",
    "\n",
    "Change it and run: sell 3 apples: subtract 3."
   ],
   "id": "t05-025"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "stock = {\"apple\": 10, \"bread\": 4}\n",
    "stock[\"apple\"] = stock[\"apple\"] + 5\n",
    "stock[\"bread\"] -= 1\n",
    "print(stock)"
   ],
   "id": "t05-026"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.3 `update(other)`: add or change several pairs at once"
   ],
   "id": "t05-027"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "student = {\"name\": \"Aylin\", \"age\": 20}\n",
    "student.update({\"age\": 21, \"city\": \"Baku\", \"email\": \"aylin@example.com\"})\n",
    "print(student)"
   ],
   "id": "t05-028"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`age` existed, so it was changed. `city` and `email` were new, so they were added.\n",
    "\n",
    "### 2.4 `setdefault(key, value)`: add only if the key is missing\n",
    "\n",
    "Change it and run: add a line `student.setdefault(\"age\", 20)`."
   ],
   "id": "t05-029"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "student = {\"name\": \"Aylin\"}\n",
    "student.setdefault(\"city\", \"Baku\")\n",
    "student.setdefault(\"name\", \"Murad\")\n",
    "print(student)"
   ],
   "id": "t05-030"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`city` was missing, so it was added. `name` already existed, so nothing changed.\n",
    "\n",
    "| Way | Key exists | Key is missing |\n",
    "| --- | --- | --- |\n",
    "| `d[key] = value` | changes the value | adds the pair |\n",
    "| `d.update({...})` | changes the values | adds the pairs |\n",
    "| `d.setdefault(key, value)` | does nothing | adds the pair |\n",
    "\n",
    "### 2.5 `pop(key)`: remove a pair and give its value back\n",
    "\n",
    "Change it and run: pop `\"city\"` too and print what is left."
   ],
   "id": "t05-031"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "student = {\"name\": \"Aylin\", \"age\": 20, \"city\": \"Baku\"}\n",
    "age = student.pop(\"age\")\n",
    "print(age)\n",
    "print(student)"
   ],
   "id": "t05-032"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A missing key gives an error, unless you give a default:\n",
    "\n",
    "```python\n",
    "student = {\"name\": \"Aylin\"}\n",
    "student.pop(\"email\")\n",
    "```\n",
    "\n",
    "```\n",
    "KeyError: 'email'\n",
    "```"
   ],
   "id": "t05-033"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "student = {\"name\": \"Aylin\"}\n",
    "print(student.pop(\"email\", \"nothing to remove\"))"
   ],
   "id": "t05-034"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.6 `del`: delete a pair"
   ],
   "id": "t05-035"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "student = {\"name\": \"Aylin\", \"age\": 20, \"city\": \"Baku\"}\n",
    "del student[\"city\"]\n",
    "print(student)"
   ],
   "id": "t05-036"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`del` does not give the value back, and a missing key is a `KeyError`.\n",
    "\n",
    "### 2.7 `popitem()`: remove the last pair\n",
    "\n",
    "Change it and run: call `popitem()` twice."
   ],
   "id": "t05-037"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "student = {\"name\": \"Aylin\", \"age\": 20, \"city\": \"Baku\"}\n",
    "last = student.popitem()\n",
    "print(last)\n",
    "print(student)"
   ],
   "id": "t05-038"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`popitem` gives the removed pair back as a tuple `(key, value)`.\n",
    "\n",
    "### 2.8 `clear()`: remove everything"
   ],
   "id": "t05-039"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "student = {\"name\": \"Aylin\", \"age\": 20}\n",
    "student.clear()\n",
    "print(student)\n",
    "print(len(student))"
   ],
   "id": "t05-040"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "| Tool | Removes | Gives back | Missing key |\n",
    "| --- | --- | --- | --- |\n",
    "| `d.pop(key)` | that pair | the value | `KeyError` |\n",
    "| `d.pop(key, default)` | that pair | the value, or the default | no error |\n",
    "| `del d[key]` | that pair | nothing | `KeyError` |\n",
    "| `d.popitem()` | the last pair | the pair as a tuple | `KeyError` if the dictionary is empty |\n",
    "| `d.clear()` | everything | nothing | no error |\n",
    "\n",
    "## 3. Keys, values, rules for keys and copying\n",
    "\n",
    "### 3.1 `keys()`, `values()`, `items()`"
   ],
   "id": "t05-041"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "prices = {\"apple\": 1.5, \"bread\": 0.8, \"milk\": 2.0}\n",
    "print(prices.keys())\n",
    "print(prices.values())\n",
    "print(prices.items())"
   ],
   "id": "t05-042"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- `keys()` gives all the keys.\n",
    "- `values()` gives all the values.\n",
    "- `items()` gives all the pairs, each one as a tuple `(key, value)`.\n",
    "\n",
    "Wrap them in `list()` when you need a real list (for example to use an index):"
   ],
   "id": "t05-043"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "prices = {\"apple\": 1.5, \"bread\": 0.8, \"milk\": 2.0}\n",
    "names = list(prices.keys())\n",
    "print(names)\n",
    "print(names[0])\n",
    "print(list(prices.values()))\n",
    "print(list(prices.items()))"
   ],
   "id": "t05-044"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.2 Calculating with the values\n",
    "\n",
    "The built-in functions you know from lists work on `values()`:\n",
    "\n",
    "Change it and run: add a fourth student with the grade 100. Which results change?"
   ],
   "id": "t05-045"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "grades = {\"Aylin\": 85, \"Murad\": 92, \"Leyla\": 78}\n",
    "print(sum(grades.values()))\n",
    "print(max(grades.values()))\n",
    "print(min(grades.values()))\n",
    "print(sum(grades.values()) / len(grades))"
   ],
   "id": "t05-046"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.3 Which key has the largest value?\n",
    "\n",
    "`max(grades)` alone compares the keys (alphabetical order). To compare by value, give `max` a `key` function (as with `max` and `key=` in the lambda lesson):\n",
    "\n",
    "Change it and run: change Leyla's grade to 99."
   ],
   "id": "t05-047"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "grades = {\"Aylin\": 85, \"Murad\": 92, \"Leyla\": 78}\n",
    "print(max(grades))\n",
    "print(max(grades, key=grades.get))\n",
    "print(min(grades, key=grades.get))"
   ],
   "id": "t05-048"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`key=grades.get` means: \"for each name, compare the value that `grades.get(name)` gives\".\n",
    "\n",
    "### 3.4 Sorting\n",
    "\n",
    "`sorted(dictionary)` gives a sorted list of the keys:\n",
    "\n",
    "Change it and run: remove `reverse=True`."
   ],
   "id": "t05-049"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "grades = {\"Murad\": 92, \"Aylin\": 85, \"Leyla\": 78}\n",
    "print(sorted(grades))\n",
    "print(sorted(grades.values()))\n",
    "print(sorted(grades, key=grades.get, reverse=True))"
   ],
   "id": "t05-050"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The last line gives the names ordered from the highest grade to the lowest.\n",
    "\n",
    "To sort the pairs by their value, sort `items()` and tell `sorted` to compare the second item of each pair. This is a small job for a lambda:\n",
    "\n",
    "Change it and run: add `reverse=True` to get the highest grade first."
   ],
   "id": "t05-051"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "grades = {\"Murad\": 92, \"Aylin\": 85, \"Leyla\": 78}\n",
    "pairs = sorted(grades.items(), key=lambda pair: pair[1])\n",
    "print(pairs)\n",
    "for name, grade in pairs:\n",
    "    print(name, grade)"
   ],
   "id": "t05-052"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.5 Keys are unique\n",
    "\n",
    "A key can appear only once. If you write it twice, the last value wins:"
   ],
   "id": "t05-053"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "ages = {\"Aylin\": 20, \"Murad\": 25, \"Aylin\": 30}\n",
    "print(ages)\n",
    "print(len(ages))"
   ],
   "id": "t05-054"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Values can repeat as often as you like:"
   ],
   "id": "t05-055"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "ages = {\"Aylin\": 20, \"Murad\": 20, \"Leyla\": 20}\n",
    "print(ages)"
   ],
   "id": "t05-056"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.6 Keys must be unchangeable (immutable)\n",
    "\n",
    "Text, numbers and tuples can be keys. A list cannot, because a list can change:"
   ],
   "id": "t05-057"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "point_names = {(0, 0): \"origin\", (1, 2): \"A\"}\n",
    "print(point_names[(1, 2)])\n",
    "\n",
    "days = {1: \"Monday\", 2: \"Tuesday\"}\n",
    "print(days[2])"
   ],
   "id": "t05-058"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```python\n",
    "wrong = {[1, 2]: \"A\"}\n",
    "```\n",
    "\n",
    "```\n",
    "TypeError: cannot use 'list' as a dict key (unhashable type: 'list')\n",
    "```\n",
    "\n",
    "### 3.7 Keys are case-sensitive"
   ],
   "id": "t05-059"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "student = {\"name\": \"Aylin\"}\n",
    "print(\"name\" in student)\n",
    "print(\"Name\" in student)"
   ],
   "id": "t05-060"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.8 The order is kept\n",
    "\n",
    "A dictionary remembers the order in which the pairs were added:"
   ],
   "id": "t05-061"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "order = {}\n",
    "order[\"first\"] = 1\n",
    "order[\"second\"] = 2\n",
    "order[\"third\"] = 3\n",
    "print(order)"
   ],
   "id": "t05-062"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.9 Copying and comparing\n",
    "\n",
    "`b = a` does not copy a dictionary. As with lists, it gives the same dictionary a second name:"
   ],
   "id": "t05-063"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = {\"x\": 1}\n",
    "b = a\n",
    "b[\"y\"] = 2\n",
    "print(a)\n",
    "print(b)"
   ],
   "id": "t05-064"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Use `.copy()` for a real, separate copy:"
   ],
   "id": "t05-065"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = {\"x\": 1}\n",
    "b = a.copy()\n",
    "b[\"y\"] = 2\n",
    "print(a)\n",
    "print(b)"
   ],
   "id": "t05-066"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Two dictionaries are equal when they have the same pairs. The order does not matter:"
   ],
   "id": "t05-067"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = {\"x\": 1, \"y\": 2}\n",
    "b = {\"y\": 2, \"x\": 1}\n",
    "print(a == b)\n",
    "print(a == {\"x\": 1})"
   ],
   "id": "t05-068"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.10 All dictionary methods in one table\n",
    "\n",
    "| Method | What it does | Changes the dictionary? | Gives back |\n",
    "| --- | --- | --- | --- |\n",
    "| `d[key]` | reads a value | no | the value (or `KeyError`) |\n",
    "| `d.get(key)` | reads a value safely | no | the value or `None` |\n",
    "| `d.get(key, default)` | reads a value safely | no | the value or the default |\n",
    "| `d[key] = value` | adds or changes a pair | yes | nothing |\n",
    "| `d.update(other)` | adds or changes several pairs | yes | `None` |\n",
    "| `d.setdefault(key, value)` | adds the pair only if the key is missing | maybe | the value of the key |\n",
    "| `d.pop(key)` | removes a pair | yes | its value |\n",
    "| `d.popitem()` | removes the last pair | yes | the pair as a tuple |\n",
    "| `del d[key]` | removes a pair | yes | nothing |\n",
    "| `d.clear()` | removes everything | yes | `None` |\n",
    "| `d.keys()` | all keys | no | the keys |\n",
    "| `d.values()` | all values | no | the values |\n",
    "| `d.items()` | all pairs | no | tuples `(key, value)` |\n",
    "| `d.copy()` | makes a separate copy | no | a new dictionary |\n",
    "\n",
    "Built-in functions that take a dictionary: `len(d)`, `list(d)`, `sorted(d)`, `max(d)`, `min(d)`, `key in d`.\n",
    "\n",
    "## 4. Going through a dictionary with loops and `if/else`\n",
    "\n",
    "### 4.1 Looping over the keys\n",
    "\n",
    "A `for` loop over a dictionary gives the keys:"
   ],
   "id": "t05-069"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "grades = {\"Aylin\": 85, \"Murad\": 92, \"Leyla\": 78}\n",
    "for name in grades:\n",
    "    print(name)"
   ],
   "id": "t05-070"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "With the key you can read the value:"
   ],
   "id": "t05-071"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "grades = {\"Aylin\": 85, \"Murad\": 92, \"Leyla\": 78}\n",
    "for name in grades:\n",
    "    print(name, grades[name])"
   ],
   "id": "t05-072"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 4.2 Looping over the values"
   ],
   "id": "t05-073"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "grades = {\"Aylin\": 85, \"Murad\": 92, \"Leyla\": 78}\n",
    "for grade in grades.values():\n",
    "    print(grade)"
   ],
   "id": "t05-074"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 4.3 Looping over the pairs: `items()`\n",
    "\n",
    "`items()` gives tuples `(key, value)`, and we unpack each one into two variables. This is the most common loop:\n",
    "\n",
    "Change it and run: add a fourth student. The loop needs no change."
   ],
   "id": "t05-075"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "grades = {\"Aylin\": 85, \"Murad\": 92, \"Leyla\": 78}\n",
    "for name, grade in grades.items():\n",
    "    print(name, \"has\", grade)"
   ],
   "id": "t05-076"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "| Loop | You get | Use it when |\n",
    "| --- | --- | --- |\n",
    "| `for key in d:` | each key | you need only the keys |\n",
    "| `for value in d.values():` | each value | you need only the values |\n",
    "| `for key, value in d.items():` | each pair | you need both (most common) |\n",
    "\n",
    "### 4.4 Loop + `if/else`: a label for every pair\n",
    "\n",
    "Change it and run: change the pass mark from 50 to 80."
   ],
   "id": "t05-077"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "grades = {\"Aylin\": 85, \"Murad\": 42, \"Leyla\": 78, \"Kamran\": 30}\n",
    "for name, grade in grades.items():\n",
    "    if grade >= 50:\n",
    "        print(name, \"passed\")\n",
    "    else:\n",
    "        print(name, \"failed\")"
   ],
   "id": "t05-078"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 4.5 Loop + `if`: sum and count"
   ],
   "id": "t05-079"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "grades = {\"Aylin\": 85, \"Murad\": 42, \"Leyla\": 78, \"Kamran\": 30}\n",
    "total = 0\n",
    "passed = 0\n",
    "for grade in grades.values():\n",
    "    total = total + grade\n",
    "    if grade >= 50:\n",
    "        passed = passed + 1\n",
    "print(\"Average:\", total / len(grades))\n",
    "print(\"Passed:\", passed)"
   ],
   "id": "t05-080"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 4.6 Finding the best by hand\n",
    "\n",
    "Change it and run: change `>` to `<` and `-1` to `101` to find the lowest grade."
   ],
   "id": "t05-081"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "grades = {\"Aylin\": 85, \"Murad\": 92, \"Leyla\": 78}\n",
    "best_name = \"\"\n",
    "best_grade = -1\n",
    "for name, grade in grades.items():\n",
    "    if grade > best_grade:\n",
    "        best_name = name\n",
    "        best_grade = grade\n",
    "print(best_name, best_grade)"
   ],
   "id": "t05-082"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "(`max(grades, key=grades.get)` does the same job, but you should understand how it works.)\n",
    "\n",
    "### 4.7 Changing the values in a loop\n",
    "\n",
    "Change it and run: add 10% instead: multiply by `1.1`."
   ],
   "id": "t05-083"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "prices = {\"apple\": 1.5, \"bread\": 0.8, \"milk\": 2.0}\n",
    "for name in prices:\n",
    "    prices[name] = prices[name] * 2\n",
    "print(prices)"
   ],
   "id": "t05-084"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Changing the values of existing keys in a loop is fine.\n",
    "\n",
    "### 4.8 Building a new dictionary with only some pairs\n",
    "\n",
    "Change it and run: keep the students who failed instead."
   ],
   "id": "t05-085"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "grades = {\"Aylin\": 85, \"Murad\": 42, \"Leyla\": 78, \"Kamran\": 30}\n",
    "passed = {}\n",
    "for name, grade in grades.items():\n",
    "    if grade >= 50:\n",
    "        passed[name] = grade\n",
    "print(passed)"
   ],
   "id": "t05-086"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 4.9 The counting pattern (very important)\n",
    "\n",
    "A dictionary is the best tool for counting how many times each thing appears. The key is the thing, the value is the count:\n",
    "\n",
    "Change it and run: add two more `\"maybe\"` votes to the list."
   ],
   "id": "t05-087"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "votes = [\"yes\", \"no\", \"yes\", \"yes\", \"no\", \"maybe\"]\n",
    "counts = {}\n",
    "for vote in votes:\n",
    "    if vote in counts:\n",
    "        counts[vote] = counts[vote] + 1\n",
    "    else:\n",
    "        counts[vote] = 1\n",
    "print(counts)"
   ],
   "id": "t05-088"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Trace table:\n",
    "\n",
    "| `vote` | already in `counts`? | `counts` after the step |\n",
    "| --- | --- | --- |\n",
    "| yes | no | `{'yes': 1}` |\n",
    "| no | no | `{'yes': 1, 'no': 1}` |\n",
    "| yes | yes | `{'yes': 2, 'no': 1}` |\n",
    "| yes | yes | `{'yes': 3, 'no': 1}` |\n",
    "| no | yes | `{'yes': 3, 'no': 2}` |\n",
    "| maybe | no | `{'yes': 3, 'no': 2, 'maybe': 1}` |\n",
    "\n",
    "With `get` and a default of 0, the `if/else` becomes one line:"
   ],
   "id": "t05-089"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "votes = [\"yes\", \"no\", \"yes\", \"yes\", \"no\", \"maybe\"]\n",
    "counts = {}\n",
    "for vote in votes:\n",
    "    counts[vote] = counts.get(vote, 0) + 1\n",
    "print(counts)"
   ],
   "id": "t05-090"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`counts.get(vote, 0)` means: \"the count so far, or 0 if this is the first time\".\n",
    "\n",
    "Counting the letters of a word works in the same way, because a `for` loop can go through a text:\n",
    "\n",
    "Change it and run: count the letters of your own name."
   ],
   "id": "t05-091"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "word = \"banana\"\n",
    "letters = {}\n",
    "for letter in word:\n",
    "    letters[letter] = letters.get(letter, 0) + 1\n",
    "print(letters)"
   ],
   "id": "t05-092"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 4.10 `while` with a dictionary\n",
    "\n",
    "Change it and run: start with 5 apples."
   ],
   "id": "t05-093"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "stock = {\"apple\": 3, \"bread\": 1}\n",
    "item = \"apple\"\n",
    "while stock[item] > 0:\n",
    "    stock[item] = stock[item] - 1\n",
    "    print(\"Sold one\", item, \"- left:\", stock[item])\n",
    "print(stock)"
   ],
   "id": "t05-094"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 4.11 Warning: do not add or remove keys while looping over a dictionary\n",
    "\n",
    "```python\n",
    "grades = {\"Aylin\": 85, \"Murad\": 42, \"Leyla\": 78}\n",
    "for name in grades:\n",
    "    if grades[name] < 50:\n",
    "        del grades[name]\n",
    "```\n",
    "\n",
    "```\n",
    "RuntimeError: dictionary changed size during iteration\n",
    "```\n",
    "\n",
    "The safe way is to loop over a copy of the keys, made with `list()`:"
   ],
   "id": "t05-095"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "grades = {\"Aylin\": 85, \"Murad\": 42, \"Leyla\": 78}\n",
    "for name in list(grades):\n",
    "    if grades[name] < 50:\n",
    "        del grades[name]\n",
    "print(grades)"
   ],
   "id": "t05-096"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5. Nested data and building dictionaries\n",
    "\n",
    "### 5.1 A list as a value\n",
    "\n",
    "Change it and run: append one more grade and print the new average."
   ],
   "id": "t05-097"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "student = {\"name\": \"Aylin\", \"grades\": [85, 92, 78]}\n",
    "print(student[\"grades\"])\n",
    "print(student[\"grades\"][0])\n",
    "print(sum(student[\"grades\"]) / len(student[\"grades\"]))\n",
    "\n",
    "student[\"grades\"].append(100)\n",
    "print(student[\"grades\"])"
   ],
   "id": "t05-098"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`student[\"grades\"]` is a list, so everything from the last lesson works on it.\n",
    "\n",
    "### 5.2 A list of dictionaries\n",
    "\n",
    "This is the most common way to store records (rows of a table). Every dictionary is one record with the same keys:\n",
    "\n",
    "Change it and run: add a fourth student record."
   ],
   "id": "t05-099"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "students = [\n",
    "    {\"name\": \"Aylin\", \"grade\": 85},\n",
    "    {\"name\": \"Murad\", \"grade\": 92},\n",
    "    {\"name\": \"Leyla\", \"grade\": 78},\n",
    "]\n",
    "print(students[0])\n",
    "print(students[1][\"name\"])\n",
    "\n",
    "for student in students:\n",
    "    print(student[\"name\"], student[\"grade\"])"
   ],
   "id": "t05-100"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`students[1]` is the second dictionary, and `students[1][\"name\"]` is the value of its key `\"name\"`.\n",
    "\n",
    "### 5.3 A dictionary inside a dictionary\n",
    "\n",
    "Change it and run: print Aylin's age."
   ],
   "id": "t05-101"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "users = {\n",
    "    \"aylin\": {\"age\": 20, \"city\": \"Baku\"},\n",
    "    \"murad\": {\"age\": 25, \"city\": \"Ganja\"},\n",
    "}\n",
    "print(users[\"murad\"])\n",
    "print(users[\"murad\"][\"city\"])\n",
    "\n",
    "for username, info in users.items():\n",
    "    print(username, \"lives in\", info[\"city\"])"
   ],
   "id": "t05-102"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 5.4 From two lists: `zip`\n",
    "\n",
    "`zip` makes pairs from two lists, and `dict` turns the pairs into a dictionary:"
   ],
   "id": "t05-103"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "names = [\"Aylin\", \"Murad\", \"Leyla\"]\n",
    "grades = [85, 92, 78]\n",
    "result = dict(zip(names, grades))\n",
    "print(result)"
   ],
   "id": "t05-104"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The same job with a loop:"
   ],
   "id": "t05-105"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "names = [\"Aylin\", \"Murad\", \"Leyla\"]\n",
    "grades = [85, 92, 78]\n",
    "result = {}\n",
    "for i in range(len(names)):\n",
    "    result[names[i]] = grades[i]\n",
    "print(result)"
   ],
   "id": "t05-106"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 5.5 From the user\n",
    "\n",
    "Each line has a name and a grade. `split` cuts the line, and we store the pair:\n",
    "\n",
    "Change it and run: type your own names and grades.\n",
    "\n",
    "When the cell asks for input, type `2`, then `Aylin 85`, then `Murad 92`."
   ],
   "id": "t05-107"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "asiman": {
     "typed": [
      "2",
      "Aylin 85",
      "Murad 92"
     ]
    }
   },
   "outputs": [],
   "source": [
    "n = int(input())\n",
    "grades = {}\n",
    "for i in range(n):\n",
    "    name, grade = input().split()\n",
    "    grades[name] = int(grade)\n",
    "print(grades)"
   ],
   "id": "t05-108"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Counting the words of a line typed by the user:\n",
    "\n",
    "Change it and run: type your own sentence.\n",
    "\n",
    "When the cell asks for input, type `red blue red green red blue`."
   ],
   "id": "t05-109"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "asiman": {
     "typed": [
      "red blue red green red blue"
     ]
    }
   },
   "outputs": [],
   "source": [
    "words = input().split()\n",
    "counts = {}\n",
    "for word in words:\n",
    "    counts[word] = counts.get(word, 0) + 1\n",
    "print(counts)"
   ],
   "id": "t05-110"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 6. Sets\n",
    "\n",
    "### 6.1 Dictionaries so far (a short review before sets)\n",
    "\n",
    "| Property | Dictionary |\n",
    "| --- | --- |\n",
    "| Written with | curly brackets and pairs: `{\"a\": 1, \"b\": 2}` |\n",
    "| You find a value by | its key |\n",
    "| Keys | unique, and unchangeable (text, numbers, tuples) |\n",
    "| Mutable (changeable) | yes: add, change, remove pairs |\n",
    "| Order | the order in which the pairs were added |\n",
    "| Typical use | looking things up by name, counting, records |\n",
    "\n",
    "Now we meet the set. A set is like a dictionary that has only keys, no values.\n",
    "\n",
    "### 6.2 What is a set?\n",
    "\n",
    "A set is a collection of unique values in no particular order. It has two special powers: it removes duplicates by itself, and it can be compared with other sets (what do they share, what is different).\n",
    "\n",
    "Real-life picture: the guests of a party. A person is either on the guest list or not. Nobody is on it twice, and the list has no \"first\" or \"second\" guest.\n",
    "\n",
    "### 6.3 Creating sets\n",
    "\n",
    "A set is written in curly brackets, with commas between the items and no colons:"
   ],
   "id": "t05-111"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = {3, 1, 2}\n",
    "print(numbers)\n",
    "print(type(numbers))\n",
    "print(len(numbers))"
   ],
   "id": "t05-112"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Duplicates disappear at once:\n",
    "\n",
    "Change it and run: write more 1s into the set. The length stays 3."
   ],
   "id": "t05-113"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = {1, 2, 2, 3, 3, 3}\n",
    "print(numbers)\n",
    "print(len(numbers))"
   ],
   "id": "t05-114"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 6.4 An empty set is `set()`, not `{}`\n",
    "\n",
    "`{}` is an empty dictionary. An empty set is written `set()`:"
   ],
   "id": "t05-115"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = {}\n",
    "b = set()\n",
    "print(type(a))\n",
    "print(type(b))\n",
    "print(len(b))"
   ],
   "id": "t05-116"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 6.5 Making a set from something else: `set()`\n",
    "\n",
    "Change it and run: make a set from the letters of your name."
   ],
   "id": "t05-117"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(set([1, 2, 2, 3, 1]))\n",
    "print(set((5, 5, 6)))\n",
    "print(sorted(set(\"banana\")))"
   ],
   "id": "t05-118"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`set()` takes a list, a tuple or a text and keeps each value once.\n",
    "\n",
    "A note about order: a set has no order, so the items of a set of texts can be printed in a different order each time you run the program. In this guide we use `sorted(...)` when we print a set of texts, so that the output is always the same. `sorted` gives a list."
   ],
   "id": "t05-119"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fruits = {\"banana\", \"apple\", \"cherry\"}\n",
    "print(sorted(fruits))"
   ],
   "id": "t05-120"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 6.6 A set has no indexes\n",
    "\n",
    "```python\n",
    "numbers = {10, 20, 30}\n",
    "print(numbers[0])\n",
    "```\n",
    "\n",
    "```\n",
    "TypeError: 'set' object is not subscriptable\n",
    "```\n",
    "\n",
    "\"Subscriptable\" means \"can be used with square brackets\". A set cannot.\n",
    "\n",
    "### 6.7 Is it in the set? `in`\n",
    "\n",
    "This is the question a set answers best, and it answers very fast, even with millions of items:"
   ],
   "id": "t05-121"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "allowed = {\"admin\", \"editor\", \"owner\"}\n",
    "print(\"admin\" in allowed)\n",
    "print(\"guest\" in allowed)\n",
    "print(\"guest\" not in allowed)"
   ],
   "id": "t05-122"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 6.8 Items must be unchangeable\n",
    "\n",
    "Numbers, text and tuples can be in a set. A list cannot:"
   ],
   "id": "t05-123"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "points = {(0, 0), (1, 2)}\n",
    "print(len(points))"
   ],
   "id": "t05-124"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```python\n",
    "wrong = {[1, 2], [3, 4]}\n",
    "```\n",
    "\n",
    "```\n",
    "TypeError: cannot use 'list' as a set element (unhashable type: 'list')\n",
    "```\n",
    "\n",
    "### 6.9 `add(item)`: add one item\n",
    "\n",
    "Change it and run: add 2 three more times."
   ],
   "id": "t05-125"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = {1, 2, 3}\n",
    "numbers.add(4)\n",
    "numbers.add(2)\n",
    "print(numbers)"
   ],
   "id": "t05-126"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Adding 2 again changes nothing, because 2 is already there.\n",
    "\n",
    "### 6.10 `update(other)`: add several items"
   ],
   "id": "t05-127"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = {1, 2, 3}\n",
    "numbers.update([3, 4, 5])\n",
    "print(numbers)"
   ],
   "id": "t05-128"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 6.11 `remove(item)` and `discard(item)`\n",
    "\n",
    "Both remove an item. They differ only when the item is missing:"
   ],
   "id": "t05-129"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = {1, 2, 3}\n",
    "numbers.remove(2)\n",
    "print(numbers)\n",
    "numbers.discard(3)\n",
    "print(numbers)"
   ],
   "id": "t05-130"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```python\n",
    "numbers = {1, 2, 3}\n",
    "numbers.remove(10)\n",
    "```\n",
    "\n",
    "```\n",
    "KeyError: 10\n",
    "```"
   ],
   "id": "t05-131"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = {1, 2, 3}\n",
    "numbers.discard(10)\n",
    "print(numbers)"
   ],
   "id": "t05-132"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 6.12 `pop()` and `clear()`\n",
    "\n",
    "`pop()` removes some item and gives it back. A set has no order, so you cannot choose which one. `clear()` removes everything."
   ],
   "id": "t05-133"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = {1, 2, 3}\n",
    "item = numbers.pop()\n",
    "print(len(numbers))\n",
    "numbers.clear()\n",
    "print(numbers)\n",
    "print(len(numbers))"
   ],
   "id": "t05-134"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "An empty set is printed as `set()`.\n",
    "\n",
    "| Method | What it does | Item is missing |\n",
    "| --- | --- | --- |\n",
    "| `s.add(x)` | adds one item |  |\n",
    "| `s.update(other)` | adds every item of `other` |  |\n",
    "| `s.remove(x)` | removes `x` | `KeyError` |\n",
    "| `s.discard(x)` | removes `x` | no error |\n",
    "| `s.pop()` | removes some item and gives it back | `KeyError` if the set is empty |\n",
    "| `s.clear()` | removes everything |  |\n",
    "\n",
    "## 7. Set operations, loops with sets, and choosing a structure\n",
    "\n",
    "### 7.1 Set operations\n",
    "\n",
    "This is what makes sets special. Take two groups of students:\n",
    "\n",
    "```\n",
    "python_class = {\"Aylin\", \"Murad\", \"Leyla\", \"Kamran\"}\n",
    "sql_class    = {\"Leyla\", \"Kamran\", \"Nigar\"}\n",
    "```\n",
    "\n",
    "### 7.2 Union: in the first or in the second (or in both)"
   ],
   "id": "t05-135"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "python_class = {\"Aylin\", \"Murad\", \"Leyla\", \"Kamran\"}\n",
    "sql_class = {\"Leyla\", \"Kamran\", \"Nigar\"}\n",
    "\n",
    "print(sorted(python_class | sql_class))\n",
    "print(sorted(python_class.union(sql_class)))"
   ],
   "id": "t05-136"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 7.3 Intersection: in the first and in the second\n",
    "\n",
    "Change it and run: add `\"Nigar\"` to `python_class`."
   ],
   "id": "t05-137"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "python_class = {\"Aylin\", \"Murad\", \"Leyla\", \"Kamran\"}\n",
    "sql_class = {\"Leyla\", \"Kamran\", \"Nigar\"}\n",
    "\n",
    "print(sorted(python_class & sql_class))\n",
    "print(sorted(python_class.intersection(sql_class)))"
   ],
   "id": "t05-138"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 7.4 Difference: in the first but not in the second"
   ],
   "id": "t05-139"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "python_class = {\"Aylin\", \"Murad\", \"Leyla\", \"Kamran\"}\n",
    "sql_class = {\"Leyla\", \"Kamran\", \"Nigar\"}\n",
    "\n",
    "print(sorted(python_class - sql_class))\n",
    "print(sorted(sql_class - python_class))\n",
    "print(sorted(python_class.difference(sql_class)))"
   ],
   "id": "t05-140"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The order matters here: `a - b` and `b - a` are different.\n",
    "\n",
    "### 7.5 Symmetric difference: in exactly one of them"
   ],
   "id": "t05-141"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "python_class = {\"Aylin\", \"Murad\", \"Leyla\", \"Kamran\"}\n",
    "sql_class = {\"Leyla\", \"Kamran\", \"Nigar\"}\n",
    "\n",
    "print(sorted(python_class ^ sql_class))\n",
    "print(sorted(python_class.symmetric_difference(sql_class)))"
   ],
   "id": "t05-142"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 7.6 All four with numbers\n",
    "\n",
    "Change it and run: change `b` to `{4, 5, 6}`."
   ],
   "id": "t05-143"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = {1, 2, 3, 4}\n",
    "b = {3, 4, 5, 6}\n",
    "\n",
    "print(a | b)\n",
    "print(a & b)\n",
    "print(a - b)\n",
    "print(b - a)\n",
    "print(a ^ b)"
   ],
   "id": "t05-144"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "| Operation | Operator | Method | Meaning | `{1, 2, 3, 4}` and `{3, 4, 5, 6}` |\n",
    "| --- | --- | --- | --- | --- |\n",
    "| Union | `a \\| b` | `a.union(b)` | in `a` or in `b` | `{1, 2, 3, 4, 5, 6}` |\n",
    "| Intersection | `a & b` | `a.intersection(b)` | in both | `{3, 4}` |\n",
    "| Difference | `a - b` | `a.difference(b)` | in `a` but not in `b` | `{1, 2}` |\n",
    "| Symmetric difference | `a ^ b` | `a.symmetric_difference(b)` | in exactly one | `{1, 2, 5, 6}` |\n",
    "\n",
    "The operators and the methods make a new set. `a` and `b` stay as they were.\n",
    "\n",
    "### 7.7 Comparing sets: subset, superset, disjoint\n",
    "\n",
    "Change it and run: add 9 to `small`. Which answers change?"
   ],
   "id": "t05-145"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "small = {1, 2}\n",
    "big = {1, 2, 3, 4}\n",
    "other = {7, 8}\n",
    "\n",
    "print(small.issubset(big))\n",
    "print(small <= big)\n",
    "print(big.issuperset(small))\n",
    "print(small.isdisjoint(other))\n",
    "print({1, 2} == {2, 1})"
   ],
   "id": "t05-146"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- `small` is a subset of `big`: every item of `small` is also in `big`.\n",
    "- `big` is a superset of `small`: it contains all of `small`.\n",
    "- Two sets are disjoint when they share nothing.\n",
    "- Two sets are equal when they have the same items. The order does not matter.\n",
    "\n",
    "### 7.8 `for` over a set"
   ],
   "id": "t05-147"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = {30, 10, 20}\n",
    "for number in sorted(numbers):\n",
    "    print(number)"
   ],
   "id": "t05-148"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A set has no order, so we loop over `sorted(numbers)` when the order matters.\n",
    "\n",
    "### 7.9 Loop + `if/else`"
   ],
   "id": "t05-149"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = {4, 7, 10, 13}\n",
    "for number in sorted(numbers):\n",
    "    if number % 2 == 0:\n",
    "        print(number, \"is even\")\n",
    "    else:\n",
    "        print(number, \"is odd\")"
   ],
   "id": "t05-150"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 7.10 Loop + `if`: sum and count"
   ],
   "id": "t05-151"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = {3, 8, 5, 12, 7}\n",
    "total = 0\n",
    "count = 0\n",
    "for number in numbers:\n",
    "    if number % 2 == 1:\n",
    "        total = total + number\n",
    "        count = count + 1\n",
    "print(\"Sum of odd numbers:\", total)\n",
    "print(\"How many:\", count)"
   ],
   "id": "t05-152"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`len`, `sum`, `min` and `max` work on sets too:"
   ],
   "id": "t05-153"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = {3, 8, 5, 12, 7}\n",
    "print(len(numbers), sum(numbers), min(numbers), max(numbers))"
   ],
   "id": "t05-154"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 7.11 Removing duplicates from a list\n",
    "\n",
    "Change it and run: use your own list with repeated numbers."
   ],
   "id": "t05-155"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [3, 5, 3, 8, 5, 3, 9]\n",
    "unique = set(numbers)\n",
    "print(len(unique))\n",
    "print(sorted(unique))"
   ],
   "id": "t05-156"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`set(numbers)` removes the duplicates in one step. The original order is lost, so we sort the result.\n",
    "\n",
    "### 7.12 Has the list any duplicates?\n",
    "\n",
    "Change it and run: remove the second 3."
   ],
   "id": "t05-157"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [3, 5, 3, 8]\n",
    "if len(numbers) != len(set(numbers)):\n",
    "    print(\"There are duplicates\")\n",
    "else:\n",
    "    print(\"All values are different\")"
   ],
   "id": "t05-158"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 7.13 Collecting what we have already seen\n",
    "\n",
    "A set is the right place to remember values while a loop runs:"
   ],
   "id": "t05-159"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [3, 5, 3, 8, 5, 9]\n",
    "seen = set()\n",
    "for number in numbers:\n",
    "    if number in seen:\n",
    "        print(number, \"appears again\")\n",
    "    else:\n",
    "        seen.add(number)"
   ],
   "id": "t05-160"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 7.14 `while` with a set"
   ],
   "id": "t05-161"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "tasks = {\"wash\", \"cook\"}\n",
    "while tasks:\n",
    "    task = tasks.pop()\n",
    "    print(\"Tasks left:\", len(tasks))\n",
    "print(\"All done\")"
   ],
   "id": "t05-162"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "An empty set counts as `False`, so `while tasks:` means \"while the set is not empty\".\n",
    "\n",
    "### 7.15 List, tuple, dictionary, set (the differences)\n",
    "\n",
    "|  | List | Tuple | Dictionary | Set |\n",
    "| --- | --- | --- | --- | --- |\n",
    "| Brackets | `[1, 2]` | `(1, 2)` | `{\"a\": 1}` | `{1, 2}` |\n",
    "| Empty | `[]` | `()` | `{}` | `set()` |\n",
    "| Ordered | yes | yes | yes (order of adding) | no |\n",
    "| Find an item by | index | index | key | not possible, only `in` |\n",
    "| Mutable (can change) | yes | no | yes | yes |\n",
    "| Duplicates | allowed | allowed | keys unique, values may repeat | not possible |\n",
    "| Typical use | items in order that change | a fixed group of values | looking up by name, counting | unique values, comparing groups |"
   ],
   "id": "t05-163"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "my_list = [1, 2, 2, 3]\n",
    "my_tuple = (1, 2, 2, 3)\n",
    "my_set = {1, 2, 2, 3}\n",
    "my_dict = {\"one\": 1, \"two\": 2}\n",
    "\n",
    "print(len(my_list), len(my_tuple), len(my_set), len(my_dict))\n",
    "print(2 in my_list, 2 in my_tuple, 2 in my_set, \"two\" in my_dict)"
   ],
   "id": "t05-164"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "How to choose:\n",
    "\n",
    "- The order matters, or you need positions: a list (or a tuple if it must not change).\n",
    "- You look things up by a name or an id, or you count things: a dictionary.\n",
    "- You only need to know \"is it there?\", or you want unique values, or you compare two groups: a set.\n",
    "\n",
    "Converting between them:"
   ],
   "id": "t05-165"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "names = [\"Aylin\", \"Murad\", \"Aylin\"]\n",
    "print(sorted(set(names)))\n",
    "print(tuple(names))\n",
    "\n",
    "grades = {\"Aylin\": 85, \"Murad\": 92}\n",
    "print(list(grades))\n",
    "print(list(grades.values()))\n",
    "print(list(grades.items()))"
   ],
   "id": "t05-166"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 8. Comprehensions\n",
    "\n",
    "### 8.1 List comprehensions\n",
    "\n",
    "A comprehension builds a new collection from another one in one line. You already know the long way.\n",
    "\n",
    "### 8.2 From a loop to a comprehension\n",
    "\n",
    "The loop:"
   ],
   "id": "t05-167"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [1, 2, 3, 4, 5]\n",
    "squares = []\n",
    "for n in numbers:\n",
    "    squares.append(n ** 2)\n",
    "print(squares)"
   ],
   "id": "t05-168"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The same thing as a list comprehension:\n",
    "\n",
    "Change it and run: change `n ** 2` to `n * 10`."
   ],
   "id": "t05-169"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [1, 2, 3, 4, 5]\n",
    "squares = [n ** 2 for n in numbers]\n",
    "print(squares)"
   ],
   "id": "t05-170"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```\n",
    "[expression for item in sequence]\n",
    "```\n",
    "\n",
    "Read it as: \"give me `n ** 2` for every `n` in `numbers`\". The square brackets say that the result is a list.\n",
    "\n",
    "| Part | In the loop | In the comprehension |\n",
    "| --- | --- | --- |\n",
    "| What goes into the new list | `squares.append(n ** 2)` | `n ** 2` (written first) |\n",
    "| Where the items come from | `for n in numbers:` | `for n in numbers` |\n",
    "| The empty list at the start | `squares = []` | not needed |\n",
    "\n",
    "More examples:"
   ],
   "id": "t05-171"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print([n * 2 for n in range(5)])\n",
    "print([word.upper() for word in [\"red\", \"green\", \"blue\"]])\n",
    "print([len(word) for word in [\"red\", \"green\", \"blue\"]])\n",
    "print([letter for letter in \"abc\"])"
   ],
   "id": "t05-172"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 8.3 A comprehension with a condition (choosing items)\n",
    "\n",
    "An `if` at the end keeps only some items:\n",
    "\n",
    "Change it and run: keep the numbers greater than 6."
   ],
   "id": "t05-173"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [3, 8, 5, 12, 7, 10]\n",
    "evens = [n for n in numbers if n % 2 == 0]\n",
    "print(evens)"
   ],
   "id": "t05-174"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This is the same as the loop:"
   ],
   "id": "t05-175"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [3, 8, 5, 12, 7, 10]\n",
    "evens = []\n",
    "for n in numbers:\n",
    "    if n % 2 == 0:\n",
    "        evens.append(n)\n",
    "print(evens)"
   ],
   "id": "t05-176"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```\n",
    "[expression for item in sequence if condition]\n",
    "```\n",
    "\n",
    "Choosing and changing together: the squares of the odd numbers.\n",
    "\n",
    "Change it and run: make the cubes of the even numbers."
   ],
   "id": "t05-177"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [1, 2, 3, 4, 5, 6]\n",
    "print([n ** 2 for n in numbers if n % 2 == 1])"
   ],
   "id": "t05-178"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 8.4 A comprehension with `if/else` (a different value for each item)\n",
    "\n",
    "To give every item a value, with two possible results, the one-line `if/else` goes at the front:"
   ],
   "id": "t05-179"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [1, 2, 3, 4]\n",
    "labels = [\"even\" if n % 2 == 0 else \"odd\" for n in numbers]\n",
    "print(labels)"
   ],
   "id": "t05-180"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Change it and run: change the pass mark to 80."
   ],
   "id": "t05-181"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "grades = [85, 42, 78, 30]\n",
    "print([\"pass\" if g >= 50 else \"fail\" for g in grades])"
   ],
   "id": "t05-182"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "|  | `if` at the end | `if/else` at the front |\n",
    "| --- | --- | --- |\n",
    "| Job | chooses items | changes every item in one of two ways |\n",
    "| Number of results | the same or fewer | always the same |\n",
    "| Example | `[n for n in numbers if n > 0]` | `[n if n > 0 else 0 for n in numbers]` |\n",
    "\n",
    "### 8.5 Comprehension, or `map` and `filter`?\n",
    "\n",
    "They do the same jobs. A comprehension is usually easier to read, because it needs no `lambda`:"
   ],
   "id": "t05-183"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [1, 2, 3, 4, 5, 6]\n",
    "\n",
    "print(list(map(lambda n: n * 2, numbers)))\n",
    "print([n * 2 for n in numbers])\n",
    "\n",
    "print(list(filter(lambda n: n % 2 == 0, numbers)))\n",
    "print([n for n in numbers if n % 2 == 0])"
   ],
   "id": "t05-184"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "| Job | `map` / `filter` | Comprehension |\n",
    "| --- | --- | --- |\n",
    "| Change every item | `list(map(lambda n: n * 2, numbers))` | `[n * 2 for n in numbers]` |\n",
    "| Choose items | `list(filter(lambda n: n > 0, numbers))` | `[n for n in numbers if n > 0]` |\n",
    "| Both | `map` around `filter` | `[n * 2 for n in numbers if n > 0]` |\n",
    "\n",
    "Reading a list of numbers from the user with a comprehension:\n",
    "\n",
    "Change it and run: type your own numbers.\n",
    "\n",
    "When the cell asks for input, type `4 8 15`."
   ],
   "id": "t05-185"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "asiman": {
     "typed": [
      "4 8 15"
     ]
    }
   },
   "outputs": [],
   "source": [
    "numbers = [int(piece) for piece in input().split()]\n",
    "print(numbers)\n",
    "print(sum(numbers))"
   ],
   "id": "t05-186"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 8.6 Two loops in one comprehension"
   ],
   "id": "t05-187"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "pairs = [(x, y) for x in [1, 2] for y in [\"a\", \"b\"]]\n",
    "print(pairs)"
   ],
   "id": "t05-188"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The first `for` is the outer loop. Use this rarely: a normal nested loop is easier to read.\n",
    "\n",
    "### 8.7 Dictionary comprehension\n",
    "\n",
    "Curly brackets and a `key: value` pair make a dictionary:\n",
    "\n",
    "```\n",
    "{key: value for item in sequence}\n",
    "```\n",
    "\n",
    "Change it and run: store the cube of each number."
   ],
   "id": "t05-189"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [1, 2, 3, 4]\n",
    "squares = {n: n ** 2 for n in numbers}\n",
    "print(squares)"
   ],
   "id": "t05-190"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The same thing as a loop:"
   ],
   "id": "t05-191"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [1, 2, 3, 4]\n",
    "squares = {}\n",
    "for n in numbers:\n",
    "    squares[n] = n ** 2\n",
    "print(squares)"
   ],
   "id": "t05-192"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The length of every word:"
   ],
   "id": "t05-193"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "words = [\"red\", \"green\", \"blue\"]\n",
    "lengths = {word: len(word) for word in words}\n",
    "print(lengths)"
   ],
   "id": "t05-194"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "From an existing dictionary, with `items()`:\n",
    "\n",
    "Change it and run: take 10% off: multiply by `0.9`."
   ],
   "id": "t05-195"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "prices = {\"apple\": 1.5, \"bread\": 0.8, \"milk\": 2.0}\n",
    "doubled = {name: price * 2 for name, price in prices.items()}\n",
    "print(doubled)"
   ],
   "id": "t05-196"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "With a condition:\n",
    "\n",
    "Change it and run: keep the students below 50."
   ],
   "id": "t05-197"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "grades = {\"Aylin\": 85, \"Murad\": 42, \"Leyla\": 78, \"Kamran\": 30}\n",
    "passed = {name: grade for name, grade in grades.items() if grade >= 50}\n",
    "print(passed)"
   ],
   "id": "t05-198"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Swapping keys and values:"
   ],
   "id": "t05-199"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "codes = {\"AZ\": \"Azerbaijan\", \"TR\": \"Turkey\"}\n",
    "by_name = {country: code for code, country in codes.items()}\n",
    "print(by_name)"
   ],
   "id": "t05-200"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 8.8 Set comprehension\n",
    "\n",
    "Curly brackets with a single value (no colon) make a set:"
   ],
   "id": "t05-201"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [1, -1, 2, -2, 3]\n",
    "print({n * n for n in numbers})\n",
    "\n",
    "words = [\"apple\", \"avocado\", \"banana\", \"blueberry\", \"cherry\"]\n",
    "print(sorted({word[0] for word in words}))"
   ],
   "id": "t05-202"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The squares of 1 and -1 are the same, so the set keeps the value once.\n",
    "\n",
    "### 8.9 Is there a tuple comprehension?\n",
    "\n",
    "No. Round brackets do not make a tuple here. Wrap a comprehension in `tuple()`:"
   ],
   "id": "t05-203"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [1, 2, 3]\n",
    "print(tuple(n * 2 for n in numbers))"
   ],
   "id": "t05-204"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "| Kind | Brackets | Example | Result |\n",
    "| --- | --- | --- | --- |\n",
    "| List | `[ ]` | `[n * 2 for n in [1, 2, 3]]` | `[2, 4, 6]` |\n",
    "| Dictionary | `{ }` with `key: value` | `{n: n * 2 for n in [1, 2, 3]}` | `{1: 2, 2: 4, 3: 6}` |\n",
    "| Set | `{ }` with one value | `{n % 2 for n in [1, 2, 3]}` | `{0, 1}` |\n",
    "\n",
    "### 8.10 When not to use a comprehension\n",
    "\n",
    "- The body needs several steps, or prints something: write a loop.\n",
    "- The line becomes long or hard to read. A comprehension must fit in your head at one glance.\n",
    "- You do not need the new collection. A comprehension is for building something, not for repeating an action.\n",
    "\n",
    "Both are correct. The loop is always a good answer.\n",
    "\n",
    "## 9. Common mistakes\n",
    "\n",
    "The red text is the real message Python shows. Where there is no message, the program runs but gives a wrong answer: the comment shows what it prints.\n",
    "\n",
    "| Mistake | What happens | Fix |\n",
    "| --- | --- | --- |\n",
    "| Reading a key that does not exist | `KeyError` | use `get`, or check with `in` first |\n",
    "| Using a position: `d[0]` | `KeyError` | a dictionary has keys, not positions |\n",
    "| Looking for a value with `in` | `False`, because `in` checks the keys | `value in d.values()` |\n",
    "| `{}` for an empty set | it is an empty dictionary | `set()` |\n",
    "| Using an index on a set: `s[0]` | `TypeError` | loop over it, or use `sorted(s)[0]` |\n",
    "| A list as a key or as a set item | `TypeError: unhashable type` | use a tuple |\n",
    "| The same key twice | the last value wins | keys are unique |\n",
    "| `b = a` to copy a dictionary | both names change together | `b = a.copy()` |\n",
    "| Removing keys while looping over the dictionary | `RuntimeError` | loop over `list(d)` |\n",
    "| `remove` an item that is not in the set | `KeyError` | use `discard` |\n",
    "| Expecting a set to keep the order | the order is not fixed | use `sorted(s)`, or a list |\n",
    "| `counts[x] = counts[x] + 1` for a new key | `KeyError` | `counts[x] = counts.get(x, 0) + 1` |\n",
    "| `if` at the wrong place in a comprehension | `SyntaxError` | choosing: `if` at the end; two results: `if/else` at the front |\n",
    "| Forgetting `.items()` when looping over pairs | `ValueError` or wrong values | `for key, value in d.items():` |\n",
    "\n",
    "Looking for a value with `in`:"
   ],
   "id": "t05-205"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "grades = {\"Aylin\": 85, \"Murad\": 92}\n",
    "print(85 in grades)\n",
    "print(85 in grades.values())"
   ],
   "id": "t05-206"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Counting without `get`:\n",
    "\n",
    "```python\n",
    "counts = {}\n",
    "counts[\"yes\"] = counts[\"yes\"] + 1\n",
    "```\n",
    "\n",
    "```\n",
    "KeyError: 'yes'\n",
    "```\n",
    "\n",
    "An `if/else` at the end of a comprehension:\n",
    "\n",
    "```python\n",
    "numbers = [1, 2, 3]\n",
    "labels = [n for n in numbers if n % 2 == 0 else \"odd\"]\n",
    "```\n",
    "\n",
    "```\n",
    "SyntaxError: invalid syntax\n",
    "```\n",
    "\n",
    "## 10. Solved problems (easy to medium-hard)\n",
    "\n",
    "Every example was run, and the outputs are real.\n",
    "\n",
    "### 10.1 Level 1: Easy\n",
    "\n",
    "Problem 1. A student card"
   ],
   "id": "t05-207"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "student = {\"name\": \"Aylin\", \"age\": 20, \"city\": \"Baku\"}\n",
    "print(\"Name:\", student[\"name\"])\n",
    "print(\"Age:\", student[\"age\"])\n",
    "print(\"City:\", student[\"city\"])"
   ],
   "id": "t05-208"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 2. A safe lookup\n",
    "\n",
    "Change it and run: type `kiwi`.\n",
    "\n",
    "When the cell asks for input, type `milk`."
   ],
   "id": "t05-209"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "asiman": {
     "typed": [
      "milk"
     ]
    }
   },
   "outputs": [],
   "source": [
    "prices = {\"apple\": 1.5, \"bread\": 0.8, \"milk\": 2.0}\n",
    "product = input()\n",
    "if product in prices:\n",
    "    print(product, \"costs\", prices[product])\n",
    "else:\n",
    "    print(product, \"is not in the shop\")"
   ],
   "id": "t05-210"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: `in` checks the keys first, so `prices[product]` can never give a `KeyError`.\n",
    "\n",
    "Problem 3. Add, change, remove"
   ],
   "id": "t05-211"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "stock = {\"apple\": 10, \"bread\": 4}\n",
    "stock[\"milk\"] = 6\n",
    "stock[\"apple\"] = stock[\"apple\"] - 3\n",
    "del stock[\"bread\"]\n",
    "print(stock)\n",
    "print(\"Products:\", len(stock))"
   ],
   "id": "t05-212"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 4. The total price of a cart"
   ],
   "id": "t05-213"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "cart = {\"apple\": 1.5, \"bread\": 0.8, \"milk\": 2.0}\n",
    "total = 0\n",
    "for price in cart.values():\n",
    "    total = total + price\n",
    "print(\"Total:\", total)\n",
    "print(\"Total:\", sum(cart.values()))"
   ],
   "id": "t05-214"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the loop and `sum(cart.values())` do the same job.\n",
    "\n",
    "Problem 5. Print a price list"
   ],
   "id": "t05-215"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "prices = {\"apple\": 1.5, \"bread\": 0.8, \"milk\": 2.0}\n",
    "for name, price in prices.items():\n",
    "    print(name, \"-\", price)"
   ],
   "id": "t05-216"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 6. How many different numbers?\n",
    "\n",
    "Change it and run: type your own numbers.\n",
    "\n",
    "When the cell asks for input, type `3 5 3 8 5 3 9`."
   ],
   "id": "t05-217"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "asiman": {
     "typed": [
      "3 5 3 8 5 3 9"
     ]
    }
   },
   "outputs": [],
   "source": [
    "numbers = list(map(int, input().split()))\n",
    "print(len(set(numbers)))"
   ],
   "id": "t05-218"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: a set keeps each value once, so its length is the number of different values.\n",
    "\n",
    "Problem 7. Common friends"
   ],
   "id": "t05-219"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "aylin_friends = {\"Murad\", \"Leyla\", \"Nigar\"}\n",
    "kamran_friends = {\"Leyla\", \"Nigar\", \"Elvin\"}\n",
    "print(sorted(aylin_friends & kamran_friends))"
   ],
   "id": "t05-220"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 8. Squares with a comprehension"
   ],
   "id": "t05-221"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "squares = [n ** 2 for n in range(1, 11)]\n",
    "print(squares)"
   ],
   "id": "t05-222"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 9. Only the positive numbers"
   ],
   "id": "t05-223"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [4, -2, 0, 7, -9, 3]\n",
    "positive = [n for n in numbers if n > 0]\n",
    "print(positive)"
   ],
   "id": "t05-224"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 10.2 Level 2: Medium\n",
    "\n",
    "Problem 10. Count the letters of a word\n",
    "\n",
    "Change it and run: count the letters of `\"banana\"`."
   ],
   "id": "t05-225"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "word = \"mississippi\"\n",
    "counts = {}\n",
    "for letter in word:\n",
    "    counts[letter] = counts.get(letter, 0) + 1\n",
    "print(counts)"
   ],
   "id": "t05-226"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the counting pattern. `get(letter, 0)` gives 0 the first time a letter appears.\n",
    "\n",
    "Problem 11. The most frequent word"
   ],
   "id": "t05-227"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "words = \"the cat and the dog and the bird\".split()\n",
    "counts = {}\n",
    "for word in words:\n",
    "    counts[word] = counts.get(word, 0) + 1\n",
    "\n",
    "most = max(counts, key=counts.get)\n",
    "print(counts)\n",
    "print(most, counts[most])"
   ],
   "id": "t05-228"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 12. The best and the worst student"
   ],
   "id": "t05-229"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "grades = {\"Aylin\": 85, \"Murad\": 92, \"Leyla\": 78, \"Kamran\": 45}\n",
    "best = max(grades, key=grades.get)\n",
    "worst = min(grades, key=grades.get)\n",
    "print(\"Best:\", best, grades[best])\n",
    "print(\"Worst:\", worst, grades[worst])"
   ],
   "id": "t05-230"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 13. A grade letter for every student"
   ],
   "id": "t05-231"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "grades = {\"Aylin\": 85, \"Murad\": 92, \"Leyla\": 68, \"Kamran\": 45}\n",
    "for name, grade in grades.items():\n",
    "    if grade >= 90:\n",
    "        letter = \"A\"\n",
    "    elif grade >= 70:\n",
    "        letter = \"B\"\n",
    "    elif grade >= 50:\n",
    "        letter = \"C\"\n",
    "    else:\n",
    "        letter = \"F\"\n",
    "    print(name, letter)"
   ],
   "id": "t05-232"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 14. Who passed? (loop and comprehension)"
   ],
   "id": "t05-233"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "grades = {\"Aylin\": 85, \"Murad\": 42, \"Leyla\": 78, \"Kamran\": 30}\n",
    "\n",
    "passed = {}\n",
    "for name, grade in grades.items():\n",
    "    if grade >= 50:\n",
    "        passed[name] = grade\n",
    "print(passed)\n",
    "\n",
    "print({name: grade for name, grade in grades.items() if grade >= 50})"
   ],
   "id": "t05-234"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 15. A dictionary from two lists"
   ],
   "id": "t05-235"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "products = [\"apple\", \"bread\", \"milk\"]\n",
    "prices = [1.5, 0.8, 2.0]\n",
    "\n",
    "by_loop = {}\n",
    "for i in range(len(products)):\n",
    "    by_loop[products[i]] = prices[i]\n",
    "print(by_loop)\n",
    "\n",
    "print(dict(zip(products, prices)))\n",
    "print({products[i]: prices[i] for i in range(len(products))})"
   ],
   "id": "t05-236"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 16. Students in only one class"
   ],
   "id": "t05-237"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "python_class = {\"Aylin\", \"Murad\", \"Leyla\", \"Kamran\"}\n",
    "sql_class = {\"Leyla\", \"Kamran\", \"Nigar\"}\n",
    "\n",
    "print(\"Both:\", sorted(python_class & sql_class))\n",
    "print(\"Only Python:\", sorted(python_class - sql_class))\n",
    "print(\"Only SQL:\", sorted(sql_class - python_class))\n",
    "print(\"Exactly one:\", sorted(python_class ^ sql_class))\n",
    "print(\"Everyone:\", sorted(python_class | sql_class))"
   ],
   "id": "t05-238"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 17. Remove duplicates and keep the order"
   ],
   "id": "t05-239"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [3, 5, 3, 8, 5, 3, 9]\n",
    "seen = set()\n",
    "unique = []\n",
    "for number in numbers:\n",
    "    if number not in seen:\n",
    "        unique.append(number)\n",
    "        seen.add(number)\n",
    "print(unique)"
   ],
   "id": "t05-240"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: `set(numbers)` alone would lose the order. The list keeps the order, and the set answers \"have I seen it?\" quickly.\n",
    "\n",
    "Problem 18. Even or odd label for every number"
   ],
   "id": "t05-241"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [1, 2, 3, 4, 5]\n",
    "labels = {n: \"even\" if n % 2 == 0 else \"odd\" for n in numbers}\n",
    "print(labels)"
   ],
   "id": "t05-242"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 10.3 Level 3: Medium-Hard\n",
    "\n",
    "Problem 19. The average grade of every student"
   ],
   "id": "t05-243"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "students = {\n",
    "    \"Aylin\": [85, 90, 78],\n",
    "    \"Murad\": [92, 88],\n",
    "    \"Leyla\": [60, 70, 80, 90],\n",
    "}\n",
    "for name, grades in students.items():\n",
    "    print(name, round(sum(grades) / len(grades), 1))\n",
    "\n",
    "averages = {name: round(sum(grades) / len(grades), 1) for name, grades in students.items()}\n",
    "print(averages)"
   ],
   "id": "t05-244"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 20. Group words by their first letter"
   ],
   "id": "t05-245"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "words = [\"apple\", \"avocado\", \"banana\", \"blueberry\", \"cherry\"]\n",
    "groups = {}\n",
    "for word in words:\n",
    "    first = word[0]\n",
    "    if first not in groups:\n",
    "        groups[first] = []\n",
    "    groups[first].append(word)\n",
    "print(groups)"
   ],
   "id": "t05-246"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: each value is a list. The first time a letter appears we create an empty list for it, then we append.\n",
    "\n",
    "Problem 21. A shop bill\n",
    "\n",
    "Change it and run: buy 10 apples."
   ],
   "id": "t05-247"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "prices = {\"apple\": 1.5, \"bread\": 0.8, \"milk\": 2.0}\n",
    "cart = {\"apple\": 4, \"milk\": 2, \"bread\": 1}\n",
    "\n",
    "total = 0\n",
    "for product, amount in cart.items():\n",
    "    cost = prices[product] * amount\n",
    "    print(product, \"x\", amount, \"=\", cost)\n",
    "    total = total + cost\n",
    "print(\"Total:\", total)"
   ],
   "id": "t05-248"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: two dictionaries with the same keys. The key from `cart` is used to look up the price.\n",
    "\n",
    "Problem 22. The student with the highest grade in a list of records"
   ],
   "id": "t05-249"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "students = [\n",
    "    {\"name\": \"Aylin\", \"grade\": 85},\n",
    "    {\"name\": \"Murad\", \"grade\": 92},\n",
    "    {\"name\": \"Leyla\", \"grade\": 78},\n",
    "]\n",
    "\n",
    "best = students[0]\n",
    "for student in students:\n",
    "    if student[\"grade\"] > best[\"grade\"]:\n",
    "        best = student\n",
    "print(best[\"name\"], best[\"grade\"])\n",
    "\n",
    "print([student[\"name\"] for student in students if student[\"grade\"] >= 80])"
   ],
   "id": "t05-250"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 23. Do two words use the same letters?"
   ],
   "id": "t05-251"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "first = \"listen\"\n",
    "second = \"silent\"\n",
    "print(set(first) == set(second))\n",
    "print(sorted(set(first) - set(\"lint\")))"
   ],
   "id": "t05-252"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 24. Numbers that appear more than once"
   ],
   "id": "t05-253"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [3, 5, 3, 8, 5, 3, 9]\n",
    "counts = {}\n",
    "for number in numbers:\n",
    "    counts[number] = counts.get(number, 0) + 1\n",
    "\n",
    "repeated = [number for number, count in counts.items() if count > 1]\n",
    "print(counts)\n",
    "print(repeated)"
   ],
   "id": "t05-254"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 25. Swap keys and values"
   ],
   "id": "t05-255"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "capitals = {\"Azerbaijan\": \"Baku\", \"Turkey\": \"Ankara\", \"Georgia\": \"Tbilisi\"}\n",
    "countries = {city: country for country, city in capitals.items()}\n",
    "print(countries)\n",
    "print(countries[\"Baku\"])"
   ],
   "id": "t05-256"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 26. Read grades, then answer questions\n",
    "\n",
    "Change it and run: type your own students.\n",
    "\n",
    "When the cell asks for input, type `3`, then `Aylin 85`, then `Murad 42`, then `Leyla 78`."
   ],
   "id": "t05-257"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "asiman": {
     "typed": [
      "3",
      "Aylin 85",
      "Murad 42",
      "Leyla 78"
     ]
    }
   },
   "outputs": [],
   "source": [
    "n = int(input())\n",
    "grades = {}\n",
    "for i in range(n):\n",
    "    name, grade = input().split()\n",
    "    grades[name] = int(grade)\n",
    "\n",
    "print(\"Students:\", len(grades))\n",
    "print(\"Average:\", sum(grades.values()) / len(grades))\n",
    "print(\"Passed:\", [name for name, grade in grades.items() if grade >= 50])\n",
    "print(\"Best:\", max(grades, key=grades.get))"
   ],
   "id": "t05-258"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: build the dictionary from the input first, then each question is one short line.\n",
    "\n",
    "## 13. Quick summary\n",
    "\n",
    "| Concept | What it does | Example |\n",
    "| --- | --- | --- |\n",
    "| Dictionary | pairs of key and value | `{\"a\": 1, \"b\": 2}` |\n",
    "| Read a value | by key | `d[\"a\"]`, `d.get(\"a\", 0)` |\n",
    "| Add or change | by key | `d[\"c\"] = 3`, `d.update({...})` |\n",
    "| Remove | by key | `d.pop(\"a\")`, `del d[\"a\"]` |\n",
    "| `keys` / `values` / `items` | all keys, values, pairs | `for k, v in d.items():` |\n",
    "| `in` | is the key there? | `\"a\" in d` |\n",
    "| Counting pattern | how many times each thing appears | `d[x] = d.get(x, 0) + 1` |\n",
    "| Set | unique values, no order | `{1, 2, 3}`, `set()` |\n",
    "| `add` / `remove` / `discard` | change a set | `s.add(4)` |\n",
    "| Union / intersection | or / and | `a \\| b`, `a & b` |\n",
    "| Difference / symmetric difference | only in `a` / in exactly one | `a - b`, `a ^ b` |\n",
    "| Unique values | remove duplicates | `set(numbers)` |\n",
    "| List comprehension | a new list in one line | `[n * 2 for n in numbers]` |\n",
    "| With a condition | choose items | `[n for n in numbers if n > 0]` |\n",
    "| With `if/else` | one of two values for every item | `[\"even\" if n % 2 == 0 else \"odd\" for n in numbers]` |\n",
    "| Dictionary comprehension | a new dictionary in one line | `{n: n ** 2 for n in numbers}` |\n",
    "| Set comprehension | a new set in one line | `{n % 2 for n in numbers}` |\n",
    "\n",
    "Golden rules\n",
    "\n",
    "1. A dictionary finds values by key, not by position.\n",
    "2. Use `get` (or check with `in`) when a key may be missing.\n",
    "3. `in` checks the keys of a dictionary, not the values.\n",
    "4. Count with `d[x] = d.get(x, 0) + 1`.\n",
    "5. An empty set is `set()`. `{}` is an empty dictionary.\n",
    "6. A set has no order and no indexes. Use `sorted(s)` when you need an order.\n",
    "7. Do not add or remove keys while looping over a dictionary. Loop over `list(d)`.\n",
    "8. In a comprehension, a choosing `if` goes at the end, and `if/else` goes at the front. If it gets hard to read, write a loop.\n",
    "\n",
    "Next: the practice notebook (topic-05-practice.ipynb), then Topic 6: file input and output, and error handling."
   ],
   "id": "t05-259"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
