{ "cells": [ { "cell_type": "markdown", "metadata": { "hide_cell": true }, "source": [ "Make me look good. Click on the cell below and press Ctrl+Enter." ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "hide_cell": true }, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", "\n", "\n", "\n" ], "text/plain": [ "" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from IPython.core.display import HTML\n", "HTML(open('css/custom.css', 'r').read())" ] }, { "cell_type": "markdown", "metadata": { "hide_cell": true }, "source": [ "
SM286D · Introduction to Applied Mathematics with Python · Spring 2020 · Uhan
\n", "\n", "
Lesson 4.
\n", "\n", "

Dictionaries

" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## This lesson..." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- Why do we need dictionaries?\n", "- Dictionary basics\n", "- Useful dictionary methods" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Why do we need dictionaries?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- Suppose we have a collection of cities and their corresponding populations as shown in the table below.\n", "\n", "| City | Population |\n", "| ---- | -------------- |\n", "| Annapolis | 38,394 |\n", "| Baltimore | 620,961 |\n", "| Frederick | 65,239 |\n", "| Rockville | 61,209 |\n", "| College Park | 30,413 |\n", "\n", "- We would like to associate each city with its corresponding population.\n", "\n", "- One way to do this would be to use lists, like this:" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Annapolis has population 38394.\n", "Baltimore has population 620961.\n", "Frederick has population 65239.\n", "Rockville has population 61209.\n", "College Park has population 30413.\n" ] } ], "source": [ "# List of cities and corresponding populations\n", "cities = ['Annapolis', 'Baltimore', 'Frederick', 'Rockville', 'College Park']\n", "population = [38394, 620961, 65239, 61209, 30413]\n", "\n", "# Print the population of each city\n", "for i in range(len(cities)):\n", " print(f'{cities[i]} has population {population[i]}.')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- Suppose now we decide to sort the cities in alphabetical order, like this:" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['Annapolis', 'Baltimore', 'College Park', 'Frederick', 'Rockville']\n" ] } ], "source": [ "# Sort list of cities in alphabetical order\n", "cities.sort()\n", "\n", "# Print to check our work\n", "print(cities)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- What happens if we run the `for` loop we wrote above to print the population of each city?" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Annapolis has population 38394.\n", "Baltimore has population 620961.\n", "College Park has population 65239.\n", "Frederick has population 61209.\n", "Rockville has population 30413.\n" ] } ], "source": [ "# Print the population of each city\n", "for i in range(len(cities)):\n", " print(f'{cities[i]} has population {population[i]}.')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- We see that the cities are no longer properly associated with their populations. 🤦 \n", "\n", "- One way to solve this kind of issue is to use a new data structure called a __dictionary__. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## What is a dictionary?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* A __dictionary__ is another way to organize a collection of items.\n", "\n", "* A dictionary maps __keys__ to __values__.\n", " - Just like a real-world dictionary maps words to definitions.\n", " \n", "* A dictionary is enclosed inside of `{ }` brackets.\n", " - Inside the brackets, the key-value pairs are separated by a colon (`key: value`).\n", " \n", "* For example, here's a dictionary containing the city populations from the table above:" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "# Create dictionary of populations by city\n", "population_by_city = {'Annapolis': 38394, 'Baltimore': 620961, 'Frederick': 65239, 'Rockville': 61209, 'College Park': 30413}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- To access the value corresponding to a particular key, we can write\n", "\n", " ```python\n", " dictionary_name[key]\n", " ```\n", "- So, to print the population of Annapolis, we can write:" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "38394\n" ] } ], "source": [ "# Print the population of Annapolis\n", "print(population_by_city['Annapolis'])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* We can also create a dictionary by starting with an empty dictionary and adding key-value pairs, like this:" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'First Name': 'Jane', 'Last Name': 'Doe', 'Company': 15, 'Alpha': 229999}\n" ] } ], "source": [ "# Create empty dictionary\n", "mid = {}\n", "\n", "# Add key-value pairs\n", "mid['First Name'] = 'Jane'\n", "mid['Last Name'] = 'Doe'\n", "mid['Company'] = 15\n", "mid['Alpha'] = 229999\n", "\n", "# Print the dictionary\n", "print(mid)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- We can remove an existing key-value pair from a dictionary with the `del` keyword:" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'First Name': 'Jane', 'Last Name': 'Doe', 'Company': 15}\n" ] } ], "source": [ "# Remove the midshipman's alpha from the dictionary\n", "del mid['Alpha']\n", "\n", "# Print to check our work\n", "print(mid)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- Some things to remember abourt dictionaries:\n", " - Keys can be strings or numbers, but keys cannot be lists.\n", " - Duplicate keys are not allowed.\n", " - Values in a Python dictionary can be any type of object (strings, numbers, lists, dictionaries, etc.)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Useful dictionary methods" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- We can apply a number of methods to dictionaries.\n", "\n", "- __Pro tip.__ In Jupyter, one way to see the methods available is to type the name of the dictionary followed by a period, and then hit the Tab key.\n", " - This actually works for any Python object, not just dictionaries.\n", "\n", "- For example, let's print the keys in the dictionary `population_by_city`:" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "dict_keys(['Annapolis', 'Baltimore', 'Frederick', 'Rockville', 'College Park'])\n" ] } ], "source": [ "# Print keys of dictionary of populations by city\n", "print(population_by_city.keys())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- It is possible to loop over the keys in a dictionary using the `.keys()` method:" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Annapolis\n", "Baltimore\n", "Frederick\n", "Rockville\n", "College Park\n" ] } ], "source": [ "# Iterate over the keys, print each of them\n", "for k in population_by_city.keys():\n", " print(k)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- You can do something similar with the values of a dictionary with the `.values()` method:" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "38394\n", "620961\n", "65239\n", "61209\n", "30413\n" ] } ], "source": [ "# Iterate over the values, print each of them\n", "for v in population_by_city.values():\n", " print(v)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- What's really great is that you can loop over the keys and corresponding values of a dictionary simultaneously with the `.items()` method:" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "City Annapolis has population 38394.\n", "City Baltimore has population 620961.\n", "City Frederick has population 65239.\n", "City Rockville has population 61209.\n", "City College Park has population 30413.\n" ] } ], "source": [ "# Print the population of each city\n", "for k, v in population_by_city.items():\n", " print(f'City {k} has population {v}.')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Classwork — on your own!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "__Problem 1.__ (PCC 6-1: Person) Use a dictionary to store information about a person you know. Store their first name, last name, age, and the city in which they live. You should have keys such as `first_name`, `last_name`, `age`, and `city`. Print each piece of information stored in your dictionary." ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "first_name: Jane\n", "last_name: Doe\n", "age: 58\n", "city: Annapolis\n", "\n", "first_name: jane\n", "last_name: doe\n", "age: 58\n", "city: annapolis\n" ] } ], "source": [ "# Write your code here\n", "# Create dictionary about person\n", "person_info = {\n", " 'first_name': 'jane',\n", " 'last_name': 'doe',\n", " 'age': 58,\n", " 'city': 'annapolis'\n", "}\n", "\n", "# Print information about person\n", "print(f\"first_name: {person_info['first_name'].title()}\")\n", "print(f\"last_name: {person_info['last_name'].title()}\")\n", "print(f\"age: {person_info['age']}\")\n", "print(f\"city: {person_info['city'].title()}\")\n", " \n", "# Print blank line\n", "print()\n", "\n", "# Alternate way to print information about person\n", "for k, v in person_info.items():\n", " print(f'{k}: {v}')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "__Problem 2__. (PCC 6-5: Rivers) Make a dictionary containing three major rivers and the country each river runs through. One key-value pair might be `'nile' : 'egypt'`.\n", "\n", " - Use a loop to print a sentence about each river, such as `The Nile runs through Egypt`.\n", " - Use a loop to print the name of each river included in the dictionary.\n", " - Use a loop to print the name of each country included in the dictionary." ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The Nile river runs through Egypt\n", "The Yellow river runs through China\n", "The Mississippi river runs through United States\n", "\n", "Here is a list of all the included rivers:\n", "Nile\n", "Yellow\n", "Mississippi\n", "\n", "Here is a list of all the included countries:\n", "Egypt\n", "China\n", "United States\n" ] } ], "source": [ "# Write your code here\n", "# Create dictionary containing countries of major rivers\n", "major_rivers = {\n", " 'nile': 'egypt',\n", " 'yellow': 'china',\n", " 'mississippi': 'united states'\n", "}\n", "\n", "# Print a sentence about each river\n", "for key, value in major_rivers.items():\n", " print(f\"The {key.title()} river runs through {value.title()}\")\n", "\n", "# Print the name of each river included in the dictionary\n", "print(\"\\nHere is a list of all the included rivers:\")\n", "for key in major_rivers.keys():\n", " print(key.title())\n", " \n", "# Print the name of each country included in the dictionary\n", "print(\"\\nHere is a list of all the included countries:\")\n", "for value in major_rivers.values():\n", " print(value.title())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "__Problem 3.__ (PCC 6-7: People) Start with the code you wrote for PCC 6-1 (Problem 1) above. Make two new dictionaries representing different people, and store all three dictionaries in a list called `people`. Loop through your list of people. As you loop through the list, print everything you know about each person." ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Here is information about person 0:\n", " first_name: jane\n", " last_name: doe\n", " age: 58\n", " city: annapolis\n", "Here is information about person 1:\n", " first_name: bob\n", " last_name: smith\n", " age: 44\n", " city: baltimore\n", "Here is information about person 2:\n", " first_name: mary\n", " last_name: jones\n", " age: 42\n", " city: detroit\n" ] } ], "source": [ "# Write your code here\n", "# Create dictionaries for containing the information for 3 people\n", "person_0 = {\n", " 'first_name': 'jane',\n", " 'last_name': 'doe',\n", " 'age': 58,\n", " 'city': 'annapolis'\n", "}\n", "\n", "person_1 = {\n", " 'first_name': 'bob',\n", " 'last_name': 'smith',\n", " 'age': 44,\n", " 'city': 'baltimore'\n", "}\n", "\n", "person_2 = {\n", " 'first_name': 'mary',\n", " 'last_name': 'jones',\n", " 'age': 42,\n", " 'city': 'detroit'\n", "}\n", "\n", "# Create a list containing the dictionaries for the 3 people\n", "people = [person_0, person_1, person_2]\n", "\n", "# Print information about each person\n", "person_number = 0\n", "for person in people:\n", " print(f\"Here is information about person {person_number}:\")\n", " person_number += 1\n", " \n", " for key, value in person.items():\n", " print(f' {key}: {value}')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "__Problem 4.__ (Rader 3.3, page 113) Three different products are made on three production lines each week. If a production line is used in a given week there is an associated setup cost. Each worker is designated to only one production line, and the pay and production of each worker depends on which line they are assigned to. In addition, each worker is assigned to one product on their assigned line. Relevant data are given below.\n", "\n", "\\begin{array}{l|c|c|c}\n", "& \\mbox{Line 1} & \\mbox{Line 2} & \\mbox{Line 3} \\\\\n", "\\hline\n", "\\mbox{Setup cost} & $2000 & $3000 & $4000 \\\\\n", "\\mbox{Product 1/worker} & 50 & 90 & 120 \\\\\n", "\\mbox{Product 2/worker} & 75 & 110 & 130 \\\\\n", "\\mbox{Product 3/worker} & 90 & 125 & 150\\\\\n", "\\mbox{Cost/worker} & \\$700 & \\$1000 & \\$1500 \\\\\n", "\\end{array}\n", "\n", "Each week we need to make 600 of product 1, 800 of product 2, and 1000 of product 3. We can use at most 20 workers.\n", "\n", "Use the data given in the table above to define four dictionaries called `setup_cost_tab`, `worker_cost_tab`, `production_tab`, and `demand_tab`. Use `1`, `2`, and `3` and `(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)` as the keys in the dictionaries (where appropriate; for instance `(2, 3)` might correspond to Product 2 made on Line 3). Print the dictionaries to check your work.\n", "\n", "_What's the point of this exercise?_ We'll need to set up similar dictionaries consisting of problem data when we learn how to formulate and solve these types of problems with Python later this semester. You'll see this in SA305 as well." ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Setup costs:\n", "{1: 2000, 2: 3000, 3: 4000}\n", "Worker costs:\n", "{1: 700, 2: 1000, 3: 1500}\n", "Production costs: (i, j) = Product i on Line j:\n", "{(1, 1): 50, (1, 2): 90, (1, 3): 120, (2, 1): 75, (2, 2): 110, (2, 3): 130, (3, 1): 90, (3, 2): 125, (3, 3): 150}\n", "Demand:\n", "{1: 600, 2: 800, 3: 1000}\n" ] } ], "source": [ "# Write your code here\n", "setup_cost_tab = {\n", " 1 : 2000,\n", " 2 : 3000,\n", " 3 : 4000,\n", "}\n", "\n", "worker_cost_tab = {\n", " 1 : 700,\n", " 2 : 1000,\n", " 3 : 1500,\n", "}\n", "\n", "production_tab = {\n", " (1, 1) : 50,\n", " (1, 2) : 90,\n", " (1, 3) : 120,\n", " (2, 1) : 75,\n", " (2, 2) : 110,\n", " (2, 3) : 130,\n", " (3, 1) : 90,\n", " (3, 2) : 125,\n", " (3, 3) : 150,\n", "}\n", "\n", "demand_tab = {\n", " 1 : 600,\n", " 2 : 800,\n", " 3 : 1000,\n", "}\n", "\n", "print('Setup costs:')\n", "print(setup_cost_tab)\n", "print('Worker costs:')\n", "print(worker_cost_tab)\n", "print('Production costs: (i, j) = Product i on Line j:')\n", "print(production_tab)\n", "print('Demand:')\n", "print(demand_tab)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "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.6.4" } }, "nbformat": 4, "nbformat_minor": 2 }