{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Lesson 9: Dictionaries\n", "\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Mapping objects and dictionaries\n", "\n", "A **mapping object** allows an arbitrary collection of objects to be indexed by an arbitrary collection of values. That's a mouthful. It is easier to understand instead by comparing to a sequence.\n", "\n", "Let's take a sequence of two strings, say a tuple containing a first and last name.\n", "\n", " name = ('jeffrey', 'lebowski')\n", "\n", "We are restricted on how we reference the sequence. I.e., the first name is `name[0]`, and the last name is `name[1]`. A mapping object could instead be indexed like `name['first name']` and `name['last name']`. You can imagine this would be very useful! A classic example in biology might be looking up amino acids that are coded for by given codons. E.g., you might want\n", "\n", " aa['CTT']\n", "\n", "to give you `'Leucine'`.\n", "\n", "Python's build-in mapping type is a **dictionary**. You might imagine that the Oxford English Dictionary might conveniently be stored as a dictionary (obviously). I.e., you would not want to store definitions that have to be referenced like\n", "\n", " oed[103829]\n", " \n", "Rather, you would like to get definitions like this:\n", "\n", " oed['computer']\n", "\n", "Importantly, note that in Python 3.5 and older **dictionaries have no sense of order**. In Python 3.6, dictionaries were stored in insertion order as an implementation improvement. In Python 3.7, dictionaries are guaranteed to be ordered in the order in which their entries were created. I therefore advise strong caution in relying on ordering in dictionaries. For safety's sake, you may be better off assuming there is no sense of order." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Dictionary syntax\n", "\n", "The syntax for creating a dictionary, as usual, is best seen through example." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'a': 6, 'b': 7, 'c': 27.6}" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "my_dict = {'a': 6, 'b': 7, 'c': 27.6}\n", "my_dict" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A dictionary is created using curly braces (`{}`). Each entry has a **key**, followed by a colon, and then the value associated with the key. In the example above, the keys are all strings, which is the most common use case. Note that the items can be of any type; in the above example, they are `int`s and a `float`.\n", "\n", "We could also create the dictionary using the built-in `dict()` function, which can take a tuple of 2-tuples, each one containing a key-value pair." ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'a': 6, 'b': 7, 'c': 27.6}" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dict((('a', 6), ('b', 7), ('c', 27.6)))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Finally, we can make a dictionary with keyword arguments to the `dict()` function." ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'a': 'yes', 'b': 'no', 'c': 'maybe'}" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dict(a='yes', b='no', c='maybe')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We do not need to have strings as the keys. In fact, any *immutable* object can be a key." ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{0: 'zero',\n", " 1.7: [1, 2, 3],\n", " (5, 6, 'dummy string'): 3.14,\n", " 'strings are immutable': 42}" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "my_dict = {\n", " 0: 'zero',\n", " 1.7: [1, 2, 3],\n", " (5, 6, 'dummy string'): 3.14,\n", " 'strings are immutable': 42\n", "}\n", "\n", "my_dict" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "However, mutable objects cannot be used as keys." ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "unhashable type: 'list'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 1\u001b[0m my_dict = {\n\u001b[1;32m 2\u001b[0m \u001b[0;34m\"immutable is ok\"\u001b[0m\u001b[0;34m:\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0;34m[\u001b[0m\u001b[0;34m\"mutable\"\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m\"not\"\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m\"ok\"\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m:\u001b[0m \u001b[0;36m5\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 4\u001b[0m }\n", "\u001b[0;31mTypeError\u001b[0m: unhashable type: 'list'" ] } ], "source": [ "my_dict = {\n", " \"immutable is ok\": 1, \n", " [\"mutable\", \"not\", \"ok\"]: 5\n", "}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Indexing dictionaries\n", "\n", "As mentioned at the beginning of the lesson, we index dictionaries by key." ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'no'" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Make a dictionary\n", "my_dict = dict(a='yes', b='no', c='maybe')\n", "\n", "# Pull out an entry\n", "my_dict['b']" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Because the indexing of dictionaries is by key and not by sequential integers, they cannot be sliced; they must be accessed element-by-element." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Useful dictionaries in bioinformatics\n", "\n", "It might be useful to quickly look up 3-letter amino acid codes. Dictionaries are particularly useful for this." ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [], "source": [ "aa_dict = {\n", " \"A\": \"Ala\",\n", " \"R\": \"Arg\",\n", " \"N\": \"Asn\",\n", " \"D\": \"Asp\",\n", " \"C\": \"Cys\",\n", " \"Q\": \"Gln\",\n", " \"E\": \"Glu\",\n", " \"G\": \"Gly\",\n", " \"H\": \"His\",\n", " \"I\": \"Ile\",\n", " \"L\": \"Leu\",\n", " \"K\": \"Lys\",\n", " \"M\": \"Met\",\n", " \"F\": \"Phe\",\n", " \"P\": \"Pro\",\n", " \"S\": \"Ser\",\n", " \"T\": \"Thr\",\n", " \"W\": \"Trp\",\n", " \"Y\": \"Tyr\",\n", " \"V\": \"Val\",\n", "}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Another useful dictionary would contain the set of codons and the amino acids they code for. This is built in the code below using the `zip()` function we learned before. To see the logic on how this is constructed, see the codon table [here](https://en.wikipedia.org/wiki/DNA_codon_table)." ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'TTT': 'F', 'TTC': 'F', 'TTA': 'L', 'TTG': 'L', 'TCT': 'S', 'TCC': 'S', 'TCA': 'S', 'TCG': 'S', 'TAT': 'Y', 'TAC': 'Y', 'TAA': '*', 'TAG': '*', 'TGT': 'C', 'TGC': 'C', 'TGA': '*', 'TGG': 'W', 'CTT': 'L', 'CTC': 'L', 'CTA': 'L', 'CTG': 'L', 'CCT': 'P', 'CCC': 'P', 'CCA': 'P', 'CCG': 'P', 'CAT': 'H', 'CAC': 'H', 'CAA': 'Q', 'CAG': 'Q', 'CGT': 'R', 'CGC': 'R', 'CGA': 'R', 'CGG': 'R', 'ATT': 'I', 'ATC': 'I', 'ATA': 'I', 'ATG': 'M', 'ACT': 'T', 'ACC': 'T', 'ACA': 'T', 'ACG': 'T', 'AAT': 'N', 'AAC': 'N', 'AAA': 'K', 'AAG': 'K', 'AGT': 'S', 'AGC': 'S', 'AGA': 'R', 'AGG': 'R', 'GTT': 'V', 'GTC': 'V', 'GTA': 'V', 'GTG': 'V', 'GCT': 'A', 'GCC': 'A', 'GCA': 'A', 'GCG': 'A', 'GAT': 'D', 'GAC': 'D', 'GAA': 'E', 'GAG': 'E', 'GGT': 'G', 'GGC': 'G', 'GGA': 'G', 'GGG': 'G'}\n" ] } ], "source": [ "# The set of DNA bases\n", "bases = ['T', 'C', 'A', 'G']\n", "\n", "# Build list of codons\n", "codon_list = []\n", "for first_base in bases:\n", " for second_base in bases:\n", " for third_base in bases:\n", " codon_list += [first_base + second_base + third_base]\n", "\n", "# The amino acids that are coded for (* = STOP codon)\n", "amino_acids = 'FFLLSSSSYY**CC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG'\n", "\n", "# Build dictionary from tuple of 2-tuples (technically an iterator, but it works)\n", "codons = dict(zip(codon_list, amino_acids))\n", "\n", "# Show that we did it\n", "print(codons)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "These two dictionaries are particularly useful, so I put them in a little module which we will discuss in the [next lesson on packages and modules](l10_packages_and_modules.ipynb)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## A dictionary is an implementation of a hash table\n", "\n", "It is useful to stop and think about how a dictionary works. Let's create a dictionary and look at where the values are stored in memory." ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "140200820028192\n", "4491306272\n", "4491306304\n", "140200819475024\n" ] } ], "source": [ "# Create dictionary\n", "my_dict = {'a': 6, 'b': 7, 'c':12.6}\n", "\n", "# Find where they are stored\n", "print(id(my_dict))\n", "print(id(my_dict['a']))\n", "print(id(my_dict['b']))\n", "print(id(my_dict['c']))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "So, each entry in the dictionary is stored at a different location in memory. The dictionary itself also has its own address. So, when I index a dictionary with a key, how does the dictionary know which address in memory to use to fetch the value I am interested in?\n", "\n", "Dictionaries use a **hash function** to do this. A hash function converts its input to an integer. For example, we can use Python's built-in hash function to convert the keys to integers." ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(940438397784053736, -8004693289631231327, -5405999133769989395)" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "hash('a'), hash('b'), hash('c')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Under the hood, Python then converts these integers to integers that could correspond to locations in memory. A collection of elements that can be indexed this way is called a **hash table**. This is a very common data structure in computing. Wikipedia has a [pretty good discussion on them](https://en.wikipedia.org/wiki/Hash_table).\n", "\n", "Given what you know about how dictionaries work, why do you think mutable objects are not acceptable as keys?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Dictionaries are mutable\n", "\n", "Dictionaries are mutable. This means that they can be changed in place. For example, if we want to add an element to a dictionary, we use simple syntax." ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'a': 6, 'b': 7, 'c': 12.6}\n", "{'a': 6, 'b': 7, 'c': 12.6, 'd': 'Bootcamp is so much fun!'}\n", "{'a': 'I was not satisfied with entry a.', 'b': 7, 'c': 12.6, 'd': 'Bootcamp is so much fun!'}\n" ] } ], "source": [ "# Remind ourselves what the dictionary is\n", "print(my_dict)\n", "\n", "# Add an entry\n", "my_dict['d'] = 'Bootcamp is so much fun!'\n", "\n", "# Look at dictionary again\n", "print(my_dict)\n", "\n", "# Change an entry\n", "my_dict['a'] = 'I was not satisfied with entry a.'\n", "\n", "# Look at it again\n", "print(my_dict)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Membership operators with dictionaries\n", "\n", "The `in` and `not in` operators work with dictionaries, but both only query keys and _not_ values. We see this again by example." ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(True, False, True)" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Make a fresh my_dict\n", "my_dict = {'a': 1, 'b': 2, 'c': 3}\n", "\n", "# in works with keys\n", "'b' in my_dict, 'd' in my_dict, 'e' not in my_dict" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Try it with values\n", "2 in my_dict" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Yup! We get `False`. Why? Because `2` is not a *key* in `my_dict`. We can also iterate over the keys in a dictionary." ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "a : 1\n", "b : 2\n", "c : 3\n" ] } ], "source": [ "for key in my_dict:\n", " print(key, ':', my_dict[key])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The best, and preferred, method, is to iterate over `key`,`value` pairs in a dictionary using the `items()` method of a dictionary." ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "a : 1\n", "b : 2\n", "c : 3\n" ] } ], "source": [ "for key, value in my_dict.items():\n", " print(key, ':', value)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note, however, that like lists, the `item`s that come out of the `my_dict.items()` iterator are *not* items in the dictionary, but copies of them. If you make changes within the `for` loop, you will not change entries in the dictionary." ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'a': 1, 'b': 2, 'c': 3}" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "for key, value in my_dict.items():\n", " value = 'this string will not be in dictionary.'\n", " \n", "my_dict" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You will, though, if you use the keys." ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'a': 'this will be in the dictionary.',\n", " 'b': 'this will be in the dictionary.',\n", " 'c': 'this will be in the dictionary.'}" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "for key, _ in my_dict.items():\n", " my_dict[key] = 'this will be in the dictionary.'\n", " \n", "my_dict" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Built-in functions for dictionaries\n", "\n", "The built-in `len()` function and `del` operation work on dictionaries. \n", "\n", "* `len(d)` gives the number of entries in dictionary `d`\n", "* `del d[k]` deletes entry with key `k` from dictionary `d`\n", "\n", "This is the first time we've encountered the `del` keyword. This keyword is used to delete variables and their values from memory. The `del` keyword can also be to delete items from lists. Let's see things in practice." ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "my_dict: {'a': 1, 'b': 2, 'c': 3, 'd': 4}\n", "my_list: [1, 2, 3, 4]\n", "length of my_dict: 4\n", "length of my_list: 4\n", "post-deleted my_dict: {'a': 1, 'c': 3, 'd': 4}\n", "post-deleted my_list: [1, 3, 4]\n" ] } ], "source": [ "# Create my_list and my_dict for reference\n", "my_dict = dict(a=1, b=2, c=3, d=4)\n", "my_list = [1, 2, 3, 4]\n", "\n", "# Print them\n", "print('my_dict:', my_dict)\n", "print('my_list:', my_list)\n", "\n", "# Get lengths\n", "print('length of my_dict:', len(my_dict))\n", "print('length of my_list:', len(my_list))\n", "\n", "# Delete a key from my_dict\n", "del my_dict['b']\n", "\n", "# Delete entry from my_list\n", "del my_list[1]\n", "\n", "# Show post-deleted objects\n", "print('post-deleted my_dict:', my_dict)\n", "print('post-deleted my_list:', my_list)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note, though, that you cannot delete an item from a tuple, since it's immutable." ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "'tuple' object doesn't support item deletion", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0mmy_tuple\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m2\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m3\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m4\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0;32mdel\u001b[0m \u001b[0mmy_tuple\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mTypeError\u001b[0m: 'tuple' object doesn't support item deletion" ] } ], "source": [ "my_tuple = (1, 2, 3, 4)\n", "del my_tuple[1]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Dictionary methods\n", "Dictionaries have several built-in methods in addition to the `items()` you have already seen. Following are a few of them, assuming the dictionary is `d`.\n", "\n", "| method | effect |\n", "|:-------|:-------|\n", "|`d.keys()`|return keys|\n", "|`d.pop(key)` | return value associated with `key` and delete `key` from `d`|\n", "|`d.values()` | return the values in `d`|\n", "|`d.get(key, default=None)` | Fetch a value in `d` by key giving a default value if `key` is missing|\n", "\n", "Let's try these out." ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "dict_keys(['a', 'b', 'c', 'd'])" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "my_dict = dict(a=1, b=2, c=3, d=4)\n", "\n", "my_dict.keys()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that this is a `dict_keys` object. We cannot index it. If, say, we wanted to sort the keys and have them index-able, we would have to convert them to a list." ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['a', 'b', 'c', 'd']" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sorted(list(my_dict.keys()))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This is not a usual use case, though, and be warned that doing then when this is not explicitly what you want can lead to bugs. Now let's try popping an entry out of the dictionary." ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "my_dict.pop('c')" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'a': 1, 'b': 2, 'd': 4}" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "my_dict" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "...and, as we expect, key `'c'` is now deleted, and its value was returned in the call to `my_dict.pop('c')`. Now, let's look at the values." ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "dict_values([1, 2, 4])" ] }, "execution_count": 24, "metadata": {}, "output_type": "execute_result" } ], "source": [ "my_dict.values()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We get a `dict_values` object, similar to the `dict_keys` object we got with the `my_dict.keys()` method. Finally, let's consider `get()`." ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "4" ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "my_dict.get('d')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This is the same as `my_dict['d']`, except that if the key `'d'` is not there, it will return a default value. Let's try using `my_dict.get()` with the deleted entry `'c'`." ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [], "source": [ "my_dict.get('c')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that there was no error (there would be if we did `my_dict['c']`), and we got `None`. We could specify a default value." ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "my_dict.get('c', 3)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You should think about what behavior you want when you attempt to get a value out of a dictionary by key. Do you want an error when the key is missing? Then use indexing. Do you want to have a (possibly `None`) default if the key is missing and no error? Then use `my_dict.get()`.\n", "\n", "You can get more information about build-in methods from the [Python documentation](https://docs.python.org/3/library/stdtypes.html#mapping-types-dict)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## List methods\n", "As you may guess, the dictionary method `pop()` has an analog that works for lists. (Why don't the dictionary `key()` and `values()` methods work for lists?) We take this opportunity to introduce a few more useful list methods. Imagine the list is called `s`.\n", "\n", "| method | effect |\n", "|:-------|:-------|\n", "|`s.pop(i)` | return value at index `i` and delete it from the list|\n", "|`s.append(x)` | Put `x` at the end of the list|\n", "|`s.insert(i, x)`| Insert `x` at index `i` in the list|\n", "|`s.remove(x)`| Remove the first occurrence of `x` from the list|\n", "|`s.reverse()` | Reverse the order of items in the list|" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Using dictionaries as kwargs\n", "\n", "A nifty feature of dictionaries is that they can be passed into functions as keyword arguments. We covered named keyword arguments in the [Intro to functions lesson](l07_intro_to_functions.ipynb). In addition to the named keyword arguments, a function can take in arbitrary keyword arguments (**not** arbitrary non-keyword arguments). This is specified in the function definition by including a last argument with a double-asterisk, `**`. The kwargs with the double-asterisk get passed in as a dictionary." ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [], "source": [ "def concatenate_sequences(a, b, **kwargs):\n", " \"\"\"Concatenate (combine) 2 or more sequences.\"\"\"\n", " seq = a + b\n", "\n", " for key in kwargs:\n", " seq += kwargs[key]\n", " \n", " return seq" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's try it!" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'TGACACCAGGGAGGGGGGGGGAAAATTTTT'" ] }, "execution_count": 29, "metadata": {}, "output_type": "execute_result" } ], "source": [ "concatenate_sequences('TGACAC', 'CAGGGA', c='GGGGGGGGG', d='AAAATTTTT')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now, imagine we have a dictionary that contains our values." ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [], "source": [ "my_dict = {\"a\": \"TGACAC\", \"b\": \"CAGGGA\", \"c\": \"GGGGGGGGG\", \"d\": \"AAAATTTTT\"}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can now pass this directly into the function by preceding it with a double asterisk." ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'TGACACCAGGGAGGGGGGGGGAAAATTTTT'" ] }, "execution_count": 31, "metadata": {}, "output_type": "execute_result" } ], "source": [ "concatenate_sequences(**my_dict)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Beautiful! This example is kind of trivial, but you can imagine that it can come in handy, e.g. with large sets of sequence fragments that you read in from a file. We will use `**kwargs` later in the bootcamp.\n", "\n", "*Question*: What is the risk in using a dictionary in this way to concatenate sequences?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Computing environment" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "CPython 3.7.7\n", "IPython 7.13.0\n", "\n", "jupyterlab 1.2.6\n" ] } ], "source": [ "%load_ext watermark\n", "%watermark -v -p jupyterlab" ] } ], "metadata": { "anaconda-cloud": {}, "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.7.7" } }, "nbformat": 4, "nbformat_minor": 4 }