{ "metadata": { "name": "", "signature": "sha256:d806710bd05c6f416dc3842515677b9246aa116881cfd0f7dd2c6b748a3a67e5" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "Let's learn more cool Python stuff." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Dictionaries\n", "\n", "Unlike lists, dictionaries are indexed by keys. Dictionaries can be used to represent unordered key-value pairs. Keys are unique and are used for looking up values assigned to them.\n", "\n", "Let's make a Spanish to English translator. We'll ignore grammar and just translate word-by-word for now." ] }, { "cell_type": "code", "collapsed": false, "input": [ "words = {\n", " 'gato': \"cat\",\n", " 'casa': \"house\",\n", " 'esta': \"is\",\n", " 'en': \"in\",\n", " 'el': \"the\",\n", " 'la': \"the\",\n", "}" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "words['gato']" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Similar to lists and strings, you can check whether a dictionary contains a given key." ] }, { "cell_type": "code", "collapsed": false, "input": [ "'gato' in words" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can also reassign keys in our dictionary:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "words['gato'] = \"dog\"\n", "words['gato']" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's change that back so we don't confuse anyone:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "words['gato'] = \"cat\"" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can also check how many key-value pairs are in our dictionary:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "len(words)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Strings have a split method which we can use to split strings with spaces into a list of words." ] }, { "cell_type": "code", "collapsed": false, "input": [ "sentence = \"el gato esta en la casa\"\n", "sentence_words = sentence.split()\n", "sentence_words" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's translate each word and save them in the list called translated_words. Let's start with an empty list and use a for loop to populate our list:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "translated_words = []\n", "for spanish_word in sentence_words:\n", " translated_words.append(words[spanish_word])" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "translated_words" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We've almost made a translated sentence! Let's join our new list of words back together with spaces in between each word." ] }, { "cell_type": "code", "collapsed": false, "input": [ "translated_sentence = \" \".join(translated_words)\n", "translated_sentence" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's put this all together into a function:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "words = {\n", " 'gato': \"cat\",\n", " 'casa': \"house\",\n", " 'esta': \"is\",\n", " 'en': \"in\",\n", " 'el': \"the\",\n", " 'la': \"the\",\n", "}\n", "\n", "def translate(sentence):\n", " spanish_words = sentence.split()\n", " english_words = []\n", " for w in spanish_words:\n", " english_words.append(words[w])\n", " return \" \".join(english_words)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "translate(\"el gato esta en la casa\")" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's add another word to our dictionary:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "words['jugo'] = \"juice\"" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "translate(\"el jugo esta en la casa\")" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "That's how we say juice in Mexican Spanish but what if we're traveling to Spain? Let's remove jugo from our dictionary and add zumo:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "del words['jugo']\n", "words['zumo'] = \"juice\"" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's try our Mexican Spanish sentence again. What should happen?" ] }, { "cell_type": "code", "collapsed": false, "input": [ "translate(\"el jugo esta en la casa\")" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now let's try our Spanish Spanish sentence:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "translate(\"el zumo esta en la casa\")" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "It's also possible to loop through the keys and values of a dictionary using the items method.\n", "Let's loop through the words dictionary and see how this works:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "for key, value in words.items():\n", " print(key, value)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Exercises:**\n", "\n", "1. Make a new py file and put that translate function in the file. Use the print function to print out some examples of using the function.\n", "\n", "2. Refactor the translate function to use a list comprehension.\n", "\n", "3. There are lots of ways to write that translate function. Just for fun, see if you can write the whole translate function in one line.\n", "\n", "**Note:** Typing out the exercises for the next section, \"Sets\", is optional. If your brain is melting, feel free to sit back, relax, and enjoy the rest of the lecture." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Tuples\n", "\n", "Tuples are similar to lists except they're immutable, which means we can't change them after they've been made.\n", "\n", "One real world use of tuples is to hold one particular record within a complex file. For example, a stock holding or a restaurant inventory.\n", "\n", "Tuples are comma-separated lists:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "food = (\"cones\", 100, 3.79)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This is sometimes called packing a tuple." ] }, { "cell_type": "code", "collapsed": false, "input": [ "food" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "type(food)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The parenthesis are often optional. They're often added for clarity. This should work too:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "food = \"sprinkles\", 10, 4.99" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "food" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's see what happens when we try to change our tuple:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "food[2] = 3" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can make an empty tuple with an empty set of parenthesis:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "empty = ()" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "empty" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "type(empty)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Any guesses how we can make a single-item tuple?" ] }, { "cell_type": "code", "collapsed": false, "input": [ "food = (3)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "food" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "type(food)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Python just sees this as a number with parenthesis around it. The commas are the important part. We need to add a comma after the number to make a single-item tuple:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "food = (3,)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "food" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "type(food)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Sometimes, unpacking a tuple is also desired." ] }, { "cell_type": "code", "collapsed": false, "input": [ "yummies = [(\"cones\", 100, 3.79), (\"sprinkles\", 10, 4.99), (\"hot fudge\", 8, 3.29), (\"nuts\", 6, 8.99)]" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "yummies[2]" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "name, amount, price = yummies[2]" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "print(\"Our ice cream shop serves \" + name + \".\")" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "print(\"The shop's inventory value for \" + name + \" is $\" + str(amount * price) + \".\")" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "print(\"All this food talk is making me hungry for \" + yummies[3][0] + \".\")" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Why not always use lists instead of tuples? Tuples use less storage space than a list. So if you are reading 1000s of small records from a file, a tuple can be an efficient way to go.\n", "\n", "A practical learning tip: When learning a new language, there are many new terms and concepts. Sometimes it is helpful to see a bigger picture of how everything comes together. I'm a lover of \"Table of Contents\" since I can scan the big picture and see where something like a tuple fits in. The official Python tutorial has a very good [Table of Contents]( https://docs.python.org/3.4/tutorial/index.html), and I sometimes take 5 minutes to just click and explore something new to me.\n", "\n", "Wow! We've come a long way today. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## List Comprehensions\n", "\n", "Now we're going to learn about list comprehensions.\n", "\n", "A list comprehension is kind of like a reverse for-loop. It makes it easy to do operations on elements in a list and return a new list." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Say we have a list of numbers:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "my_favorite_numbers = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now let's make a new list that contains a square of every number in our list." ] }, { "cell_type": "code", "collapsed": false, "input": [ "squared_numbers = []\n", "for n in my_favorite_numbers:\n", " squared_numbers.append(n * n)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "squared_numbers" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Stop for questions?:** Does this look familiar? Any questions about this?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now let's do the same thing by using a list comprehension instead:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "squared_numbers = [n * n for n in my_favorite_numbers]" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "squared_numbers" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note how our list comprehension is written within the brackets: The list we're looping over (my_favorite_numbers) is written at the end whereas the action inside of the for-loop is written first: n * n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "First written as a conventional 'for' loop:\n", "
\n",
      "squared_numbers = []\n",
      "for n in my_favorite_numbers:\n",
      "    squared_numbers.append(n * n)\n",
      "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And then written as a list comprehension:\n", "
\n",
      "squared_numbers = [n * n for n in my_favorite_numbers]\n",
      "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Look for the new list being created, the iteration being done over the orignal list and the transformation being done on each element. List comprehensions are just a cleaner way of building lists from other iterables." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Improving our work\n", "\n", "Let's revisit a problem we've already solved in Danny's lecture on lists:\n", "\n", "Pick every name from a list that begins with a vowel.\n", "\n", "We started with a list of names first:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "names = [\"Danny\", \"Audrey\", \"Rise\", \"Alain\"]" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Then we filtered names like this:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "vowel_names = []\n", "for name in names:\n", " if name[0] in \"AEIOU\":\n", " vowel_names.append(name)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "vowel_names" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here's another way to grab all names starting with a vowel, using list comprehensions:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "vowel_names = [name for name in names if name[0] in \"AEIOU\"]" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "vowel_names" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] } ], "metadata": {} } ] }