{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## CS 200: Dicts and Files in Python\n", "\n", "This notebook mirrors the Google Python Course: Dict - Files\n", "\n", "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Video: \n", "\n", "See Dictionaries from Socratica\n", "\n", "\n", "Python supports dictionaries as a native data type. Dictionaries, or dicts, are content addressable arrays of data. They are normally implemented as hash tables. We wlll see how to create a hash table from scratch later on.\n", "\n", "Strings are delimited by quotes. Lists are delimited by square balckets. Tuples are delimited by parentheses. Dicts are delimited by curly brackets." ] }, { "cell_type": "code", "execution_count": 63, "metadata": {}, "outputs": [], "source": [ "d = {}" ] }, { "cell_type": "code", "execution_count": 64, "metadata": {}, "outputs": [], "source": [ "d['a'] = 'alpha'" ] }, { "cell_type": "code", "execution_count": 65, "metadata": {}, "outputs": [], "source": [ "d['b'] = 'beta'" ] }, { "cell_type": "code", "execution_count": 66, "metadata": {}, "outputs": [], "source": [ "d['c'] = 'gamma'" ] }, { "cell_type": "code", "execution_count": 67, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'a': 'alpha', 'b': 'beta', 'c': 'gamma'}" ] }, "execution_count": 67, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d" ] }, { "cell_type": "code", "execution_count": 68, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 68, "metadata": {}, "output_type": "execute_result" } ], "source": [ "len(d)" ] }, { "cell_type": "code", "execution_count": 69, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'beta'" ] }, "execution_count": 69, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d['b']" ] }, { "cell_type": "code", "execution_count": 70, "metadata": {}, "outputs": [ { "ename": "KeyError", "evalue": "'s'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mKeyError\u001b[0m Traceback (most recent call last)", "Input \u001b[0;32mIn [70]\u001b[0m, in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0m d[\u001b[38;5;124m'\u001b[39m\u001b[38;5;124ms\u001b[39m\u001b[38;5;124m'\u001b[39m]\n", "\u001b[0;31mKeyError\u001b[0m: 's'" ] } ], "source": [ "d['s']" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Python lists and strings are indexed by position, e.g., 0, 1, 2. Python dicts are indexed by content. Above we assign the string 'alpha' to the dict entry 'a'. We access the values using these labels as well.\n", "\n", "Dicts, like lists, but unlike tuples, are mutable." ] }, { "cell_type": "code", "execution_count": 71, "metadata": {}, "outputs": [], "source": [ "d['b'] = 'new value'" ] }, { "cell_type": "code", "execution_count": 72, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'new value'" ] }, "execution_count": 72, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d['b'] " ] }, { "cell_type": "code", "execution_count": 73, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'a': 'alpha', 'b': 'new value', 'c': 'gamma'}" ] }, "execution_count": 73, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d" ] }, { "cell_type": "code", "execution_count": 74, "metadata": {}, "outputs": [ { "ename": "KeyError", "evalue": "'z'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mKeyError\u001b[0m Traceback (most recent call last)", "Input \u001b[0;32mIn [74]\u001b[0m, in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0m d[\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mz\u001b[39m\u001b[38;5;124m'\u001b[39m]\n", "\u001b[0;31mKeyError\u001b[0m: 'z'" ] } ], "source": [ "d['z']" ] }, { "cell_type": "code", "execution_count": 75, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 75, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'a' in d" ] }, { "cell_type": "code", "execution_count": 76, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 76, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'z' in d" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you ask for a value that is not in the dict, python throws a KeyError. You may use the in operator first to check if the value is in the dictionary." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "By default, iterating over a dict uses the keys." ] }, { "cell_type": "code", "execution_count": 77, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "a\n", "b\n", "c\n" ] } ], "source": [ "for key in d:\n", " print (key)" ] }, { "cell_type": "code", "execution_count": 78, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "alpha\n", "new value\n", "gamma\n" ] } ], "source": [ "for key in d:\n", " print (d[key])" ] }, { "cell_type": "code", "execution_count": 79, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['a', 'b', 'c']" ] }, "execution_count": 79, "metadata": {}, "output_type": "execute_result" } ], "source": [ "[k for k in d]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### dict methods\n", "\n", "Using dir() we can see other native dict methods." ] }, { "cell_type": "code", "execution_count": 80, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['__class__',\n", " '__class_getitem__',\n", " '__contains__',\n", " '__delattr__',\n", " '__delitem__',\n", " '__dir__',\n", " '__doc__',\n", " '__eq__',\n", " '__format__',\n", " '__ge__',\n", " '__getattribute__',\n", " '__getitem__',\n", " '__gt__',\n", " '__hash__',\n", " '__init__',\n", " '__init_subclass__',\n", " '__ior__',\n", " '__iter__',\n", " '__le__',\n", " '__len__',\n", " '__lt__',\n", " '__ne__',\n", " '__new__',\n", " '__or__',\n", " '__reduce__',\n", " '__reduce_ex__',\n", " '__repr__',\n", " '__reversed__',\n", " '__ror__',\n", " '__setattr__',\n", " '__setitem__',\n", " '__sizeof__',\n", " '__str__',\n", " '__subclasshook__',\n", " 'clear',\n", " 'copy',\n", " 'fromkeys',\n", " 'get',\n", " 'items',\n", " 'keys',\n", " 'pop',\n", " 'popitem',\n", " 'setdefault',\n", " 'update',\n", " 'values']" ] }, "execution_count": 80, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dir(d)" ] }, { "cell_type": "code", "execution_count": 81, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "dict_keys(['a', 'b', 'c'])" ] }, "execution_count": 81, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d.keys()" ] }, { "cell_type": "code", "execution_count": 82, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "dict_keys" ] }, "execution_count": 82, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(d.keys())" ] }, { "cell_type": "code", "execution_count": 83, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['a', 'b', 'c']" ] }, "execution_count": 83, "metadata": {}, "output_type": "execute_result" } ], "source": [ "list(d.keys())" ] }, { "cell_type": "code", "execution_count": 84, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "a\n", "b\n", "c\n" ] } ], "source": [ "for key in d.keys():\n", " print (key)" ] }, { "cell_type": "code", "execution_count": 85, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "alpha\n", "new value\n", "gamma\n" ] } ], "source": [ "for value in d.values():\n", " print (value)" ] }, { "cell_type": "code", "execution_count": 86, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "dict_items([('a', 'alpha'), ('b', 'new value'), ('c', 'gamma')])" ] }, "execution_count": 86, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d.items()" ] }, { "cell_type": "code", "execution_count": 87, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "a alpha\n", "b new value\n", "c gamma\n" ] } ], "source": [ "for key, value in d.items():\n", " print (key, value)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Tuple Assignment" ] }, { "cell_type": "code", "execution_count": 88, "metadata": {}, "outputs": [], "source": [ "(a, b, c) = 1,2,3" ] }, { "cell_type": "code", "execution_count": 89, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 89, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a" ] }, { "cell_type": "code", "execution_count": 90, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 90, "metadata": {}, "output_type": "execute_result" } ], "source": [ "b" ] }, { "cell_type": "code", "execution_count": 91, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 91, "metadata": {}, "output_type": "execute_result" } ], "source": [ "c" ] }, { "cell_type": "code", "execution_count": 92, "metadata": {}, "outputs": [], "source": [ "(a,b) = b,a" ] }, { "cell_type": "code", "execution_count": 93, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 93, "metadata": {}, "output_type": "execute_result" } ], "source": [ "b" ] }, { "cell_type": "code", "execution_count": 94, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 94, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We were able to swap a and b without using a temporary variable.\n", "\n", "### copy()\n", "\n", "We will try the following code in PythonTutor\n", "\n", "
\n",
    "d = {}\n",
    "d['a'] = 'alpha'\n",
    "d['b'] = 'beta'\n",
    "d['c'] = 'gamma'\n",
    "newd = d.copy()\n",
    "
\n" ] }, { "cell_type": "code", "execution_count": 95, "metadata": {}, "outputs": [], "source": [ "newd = d.copy()" ] }, { "cell_type": "code", "execution_count": 62, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'a': 'alpha', 'b': 'new value', 'c': 'gamma'}" ] }, "execution_count": 62, "metadata": {}, "output_type": "execute_result" } ], "source": [ "newd" ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 35, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d == newd" ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [], "source": [ "newd['a'] = 'new alpha'" ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'a': 'new alpha', 'b': 'new value', 'c': 'gamma'}" ] }, "execution_count": 37, "metadata": {}, "output_type": "execute_result" } ], "source": [ "newd" ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 38, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d == newd" ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'a': 'alpha', 'b': 'new value', 'c': 'gamma'}" ] }, "execution_count": 39, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d" ] }, { "cell_type": "code", "execution_count": 40, "metadata": {}, "outputs": [], "source": [ "newd.clear()" ] }, { "cell_type": "code", "execution_count": 41, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{}" ] }, "execution_count": 41, "metadata": {}, "output_type": "execute_result" } ], "source": [ "newd" ] }, { "cell_type": "code", "execution_count": 42, "metadata": {}, "outputs": [], "source": [ "keys = ['a', 'b', 'c']" ] }, { "cell_type": "code", "execution_count": 43, "metadata": {}, "outputs": [], "source": [ "d2 = dict.fromkeys(keys)" ] }, { "cell_type": "code", "execution_count": 44, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'a': None, 'b': None, 'c': None}" ] }, "execution_count": 44, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d2" ] }, { "cell_type": "code", "execution_count": 45, "metadata": {}, "outputs": [], "source": [ "d3 = dict.fromkeys(keys, 'something')" ] }, { "cell_type": "code", "execution_count": 46, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'a': 'something', 'b': 'something', 'c': 'something'}" ] }, "execution_count": 46, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d3" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "fromkeys() is a class method. It is invoked using the class, not an instance of the class. It creates a new dict with the given keys and value. If no value is specified, it uses 'None', a special python value." ] }, { "cell_type": "code", "execution_count": 47, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'a': 'alpha', 'b': 'new value', 'c': 'gamma'}" ] }, "execution_count": 47, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d" ] }, { "cell_type": "code", "execution_count": 48, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'alpha'" ] }, "execution_count": 48, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d.get('a')" ] }, { "cell_type": "code", "execution_count": 49, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'alpha'" ] }, "execution_count": 49, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d['a']" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "get() is an alternative to the square bracket notation." ] }, { "cell_type": "code", "execution_count": 50, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'gamma'" ] }, "execution_count": 50, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d.pop('c')" ] }, { "cell_type": "code", "execution_count": 51, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'a': 'alpha', 'b': 'new value'}" ] }, "execution_count": 51, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d" ] }, { "cell_type": "code", "execution_count": 52, "metadata": {}, "outputs": [ { "ename": "KeyError", "evalue": "'z'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mKeyError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m/tmp/ipykernel_2112319/1908275066.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0md\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mpop\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'z'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mKeyError\u001b[0m: 'z'" ] } ], "source": [ "d.pop('z')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "pop(key) removes the item with the given key from the dict and returns its value. It there is no item with the given key, python throws a KeyError." ] }, { "cell_type": "code", "execution_count": 53, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "('b', 'new value')" ] }, "execution_count": 53, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d.popitem()" ] }, { "cell_type": "code", "execution_count": 54, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'a': 'alpha'}" ] }, "execution_count": 54, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d" ] }, { "cell_type": "code", "execution_count": 55, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "('a', 'alpha')" ] }, "execution_count": 55, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d.popitem()" ] }, { "cell_type": "code", "execution_count": 56, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{}" ] }, "execution_count": 56, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d" ] }, { "cell_type": "code", "execution_count": 57, "metadata": {}, "outputs": [ { "ename": "KeyError", "evalue": "'popitem(): dictionary is empty'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mKeyError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m/tmp/ipykernel_2112319/3489706405.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0md\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mpopitem\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mKeyError\u001b[0m: 'popitem(): dictionary is empty'" ] } ], "source": [ "d.popitem()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "popitem() removes the last item from the dict. If the dict is empty, python throws a KeyError. Note: pop() returns the key, and popitem() returns the key-value pair as a dictionary. Both remove the last item." ] }, { "cell_type": "code", "execution_count": 58, "metadata": {}, "outputs": [], "source": [ "person = {'Name': 'Jon', 'Age': 10}" ] }, { "cell_type": "code", "execution_count": 59, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'Name': 'Jon', 'Age': 10}" ] }, "execution_count": 59, "metadata": {}, "output_type": "execute_result" } ], "source": [ "person" ] }, { "cell_type": "code", "execution_count": 60, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Jon'" ] }, "execution_count": 60, "metadata": {}, "output_type": "execute_result" } ], "source": [ "person.setdefault('Name', None)" ] }, { "cell_type": "code", "execution_count": 61, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'unknown'" ] }, "execution_count": 61, "metadata": {}, "output_type": "execute_result" } ], "source": [ "person.setdefault('Gender','unknown')" ] }, { "cell_type": "code", "execution_count": 62, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'Name': 'Jon', 'Age': 10, 'Gender': 'unknown'}" ] }, "execution_count": 62, "metadata": {}, "output_type": "execute_result" } ], "source": [ "person" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The setdefault() method provides a way to handle missing keys in a dict, avoiding the dreaded KeyError." ] }, { "cell_type": "code", "execution_count": 63, "metadata": {}, "outputs": [], "source": [ "d = {1: 'one', 2: 'three'}" ] }, { "cell_type": "code", "execution_count": 64, "metadata": {}, "outputs": [], "source": [ "d2 = {2: 'two', 3: \"three\"}" ] }, { "cell_type": "code", "execution_count": 65, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{1: 'one', 2: 'three'}" ] }, "execution_count": 65, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d" ] }, { "cell_type": "code", "execution_count": 66, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{2: 'two', 3: 'three'}" ] }, "execution_count": 66, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d2" ] }, { "cell_type": "code", "execution_count": 67, "metadata": {}, "outputs": [], "source": [ "d.update(d2)" ] }, { "cell_type": "code", "execution_count": 68, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{1: 'one', 2: 'two', 3: 'three'}" ] }, "execution_count": 68, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The update() method merges two dictionaries, changing or inserting items as needed\n", "\n", "### del() function\n", "\n", "Finally, the del() function can be used with variables, lists, and dicts. It removes the given item. As they say in the CIA, it terminates with extreme prejudice. " ] }, { "cell_type": "code", "execution_count": 69, "metadata": {}, "outputs": [], "source": [ "x = 4" ] }, { "cell_type": "code", "execution_count": 70, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "4" ] }, "execution_count": 70, "metadata": {}, "output_type": "execute_result" } ], "source": [ "x" ] }, { "cell_type": "code", "execution_count": 71, "metadata": {}, "outputs": [], "source": [ "del(x)" ] }, { "cell_type": "code", "execution_count": 72, "metadata": {}, "outputs": [ { "ename": "NameError", "evalue": "name 'x' is not defined", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m/tmp/ipykernel_2112319/32546335.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mx\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mNameError\u001b[0m: name 'x' is not defined" ] } ], "source": [ "x" ] }, { "cell_type": "code", "execution_count": 73, "metadata": {}, "outputs": [], "source": [ "lst = [1,2,3,4]" ] }, { "cell_type": "code", "execution_count": 74, "metadata": {}, "outputs": [], "source": [ "del(lst[0])" ] }, { "cell_type": "code", "execution_count": 75, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[2, 3, 4]" ] }, "execution_count": 75, "metadata": {}, "output_type": "execute_result" } ], "source": [ "lst" ] }, { "cell_type": "code", "execution_count": 76, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{1: 'one', 2: 'two', 3: 'three'}" ] }, "execution_count": 76, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d " ] }, { "cell_type": "code", "execution_count": 77, "metadata": {}, "outputs": [], "source": [ "del(d[1])" ] }, { "cell_type": "code", "execution_count": 78, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{2: 'two', 3: 'three'}" ] }, "execution_count": 78, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Files\n", "\n", "### Video:\n", "\n", "See Text Files from Socratica\n", "\n", "It is quite common for computer programs to use files for input and output. That is, a program may read from a file (input) or write to a file (output). It may also add to the end of an existing file (append).\n", "\n", "The open(filename, mode) command is used for both reading and writing. The filename specifes the actual file. The mode is a string value of either r (read), w (write), a (append), or x (create a file, return an error if it already exists). You should call close() once you are finished reading or writing." ] }, { "cell_type": "code", "execution_count": 103, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on built-in function open in module io:\n", "\n", "open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)\n", " Open file and return a stream. Raise OSError upon failure.\n", " \n", " file is either a text or byte string giving the name (and the path\n", " if the file isn't in the current working directory) of the file to\n", " be opened or an integer file descriptor of the file to be\n", " wrapped. (If a file descriptor is given, it is closed when the\n", " returned I/O object is closed, unless closefd is set to False.)\n", " \n", " mode is an optional string that specifies the mode in which the file\n", " is opened. It defaults to 'r' which means open for reading in text\n", " mode. Other common values are 'w' for writing (truncating the file if\n", " it already exists), 'x' for creating and writing to a new file, and\n", " 'a' for appending (which on some Unix systems, means that all writes\n", " append to the end of the file regardless of the current seek position).\n", " In text mode, if encoding is not specified the encoding used is platform\n", " dependent: locale.getpreferredencoding(False) is called to get the\n", " current locale encoding. (For reading and writing raw bytes use binary\n", " mode and leave encoding unspecified.) The available modes are:\n", " \n", " ========= ===============================================================\n", " Character Meaning\n", " --------- ---------------------------------------------------------------\n", " 'r' open for reading (default)\n", " 'w' open for writing, truncating the file first\n", " 'x' create a new file and open it for writing\n", " 'a' open for writing, appending to the end of the file if it exists\n", " 'b' binary mode\n", " 't' text mode (default)\n", " '+' open a disk file for updating (reading and writing)\n", " 'U' universal newline mode (deprecated)\n", " ========= ===============================================================\n", " \n", " The default mode is 'rt' (open for reading text). For binary random\n", " access, the mode 'w+b' opens and truncates the file to 0 bytes, while\n", " 'r+b' opens the file without truncation. The 'x' mode implies 'w' and\n", " raises an `FileExistsError` if the file already exists.\n", " \n", " Python distinguishes between files opened in binary and text modes,\n", " even when the underlying operating system doesn't. Files opened in\n", " binary mode (appending 'b' to the mode argument) return contents as\n", " bytes objects without any decoding. In text mode (the default, or when\n", " 't' is appended to the mode argument), the contents of the file are\n", " returned as strings, the bytes having been first decoded using a\n", " platform-dependent encoding or using the specified encoding if given.\n", " \n", " 'U' mode is deprecated and will raise an exception in future versions\n", " of Python. It has no effect in Python 3. Use newline to control\n", " universal newlines mode.\n", " \n", " buffering is an optional integer used to set the buffering policy.\n", " Pass 0 to switch buffering off (only allowed in binary mode), 1 to select\n", " line buffering (only usable in text mode), and an integer > 1 to indicate\n", " the size of a fixed-size chunk buffer. When no buffering argument is\n", " given, the default buffering policy works as follows:\n", " \n", " * Binary files are buffered in fixed-size chunks; the size of the buffer\n", " is chosen using a heuristic trying to determine the underlying device's\n", " \"block size\" and falling back on `io.DEFAULT_BUFFER_SIZE`.\n", " On many systems, the buffer will typically be 4096 or 8192 bytes long.\n", " \n", " * \"Interactive\" text files (files for which isatty() returns True)\n", " use line buffering. Other text files use the policy described above\n", " for binary files.\n", " \n", " encoding is the name of the encoding used to decode or encode the\n", " file. This should only be used in text mode. The default encoding is\n", " platform dependent, but any encoding supported by Python can be\n", " passed. See the codecs module for the list of supported encodings.\n", " \n", " errors is an optional string that specifies how encoding errors are to\n", " be handled---this argument should not be used in binary mode. Pass\n", " 'strict' to raise a ValueError exception if there is an encoding error\n", " (the default of None has the same effect), or pass 'ignore' to ignore\n", " errors. (Note that ignoring encoding errors can lead to data loss.)\n", " See the documentation for codecs.register or run 'help(codecs.Codec)'\n", " for a list of the permitted encoding error strings.\n", " \n", " newline controls how universal newlines works (it only applies to text\n", " mode). It can be None, '', '\\n', '\\r', and '\\r\\n'. It works as\n", " follows:\n", " \n", " * On input, if newline is None, universal newlines mode is\n", " enabled. Lines in the input can end in '\\n', '\\r', or '\\r\\n', and\n", " these are translated into '\\n' before being returned to the\n", " caller. If it is '', universal newline mode is enabled, but line\n", " endings are returned to the caller untranslated. If it has any of\n", " the other legal values, input lines are only terminated by the given\n", " string, and the line ending is returned to the caller untranslated.\n", " \n", " * On output, if newline is None, any '\\n' characters written are\n", " translated to the system default line separator, os.linesep. If\n", " newline is '' or '\\n', no translation takes place. If newline is any\n", " of the other legal values, any '\\n' characters written are translated\n", " to the given string.\n", " \n", " If closefd is False, the underlying file descriptor will be kept open\n", " when the file is closed. This does not work when a file name is given\n", " and must be True in that case.\n", " \n", " A custom opener can be used by passing a callable as *opener*. The\n", " underlying file descriptor for the file object is then obtained by\n", " calling *opener* with (*file*, *flags*). *opener* must return an open\n", " file descriptor (passing os.open as *opener* results in functionality\n", " similar to passing None).\n", " \n", " open() returns a file object whose type depends on the mode, and\n", " through which the standard file operations such as reading and writing\n", " are performed. When open() is used to open a file in a text mode ('w',\n", " 'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open\n", " a file in a binary mode, the returned class varies: in read binary\n", " mode, it returns a BufferedReader; in write binary and append binary\n", " modes, it returns a BufferedWriter, and in read/write mode, it returns\n", " a BufferedRandom.\n", " \n", " It is also possible to use a string or bytearray as a file for both\n", " reading and writing. For strings StringIO can be used like a file\n", " opened in a text mode, and for bytes a BytesIO can be used like a file\n", " opened in a binary mode.\n", "\n" ] } ], "source": [ "help(open)" ] }, { "cell_type": "code", "execution_count": 104, "metadata": {}, "outputs": [], "source": [ "f = open(\"testfile\", 'w')" ] }, { "cell_type": "code", "execution_count": 105, "metadata": {}, "outputs": [], "source": [ "for x in \"this is a test\".split():\n", " f.write(x)\n", " f.write('\\n')" ] }, { "cell_type": "code", "execution_count": 106, "metadata": {}, "outputs": [], "source": [ "f.close()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "open() creates an iterator which can process the file one line at a time." ] }, { "cell_type": "code", "execution_count": 107, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "this\n", "is\n", "a\n", "test\n" ] } ], "source": [ "for line in open(\"testfile\", \"r\"):\n", " print(line, end='')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note: file is implicitly closed once the iteration is complete." ] }, { "cell_type": "code", "execution_count": 86, "metadata": {}, "outputs": [], "source": [ "f = open(\"testfile\", 'a')\n", "f.write(\"this is another line\\n\")\n", "f.close()" ] }, { "cell_type": "code", "execution_count": 87, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "this\n", "\n", "is\n", "\n", "a\n", "\n", "test\n", "\n", "this is another line\n", "\n" ] } ], "source": [ "for line in open(\"testfile\", 'r'):\n", " print(line)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### word count\n", "\n", "We will now read in the file, split it up into words, and then use a dict to count how many times each word occurs. We use the read() method which reads the entire file." ] }, { "cell_type": "code", "execution_count": 88, "metadata": {}, "outputs": [], "source": [ "f = open(\"testfile\", 'r')" ] }, { "cell_type": "code", "execution_count": 89, "metadata": {}, "outputs": [], "source": [ "lines = f.read()" ] }, { "cell_type": "code", "execution_count": 90, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'this\\nis\\na\\ntest\\nthis is another line\\n'" ] }, "execution_count": 90, "metadata": {}, "output_type": "execute_result" } ], "source": [ "lines" ] }, { "cell_type": "code", "execution_count": 91, "metadata": {}, "outputs": [], "source": [ "words = lines.split()" ] }, { "cell_type": "code", "execution_count": 92, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['this', 'is', 'a', 'test', 'this', 'is', 'another', 'line']" ] }, "execution_count": 92, "metadata": {}, "output_type": "execute_result" } ], "source": [ "words" ] }, { "cell_type": "code", "execution_count": 93, "metadata": {}, "outputs": [], "source": [ "count = {}" ] }, { "cell_type": "code", "execution_count": 94, "metadata": {}, "outputs": [], "source": [ "for word in words:\n", " if word in count:\n", " count[word] += 1\n", " else:\n", " count[word] = 1" ] }, { "cell_type": "code", "execution_count": 111, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'this': 3, 'is': 5, 'a': 1, 'test': 1, 'another': 4, 'linethis': 2, 'line': 2}" ] }, "execution_count": 111, "metadata": {}, "output_type": "execute_result" } ], "source": [ "count" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "End of dict-files notebook." ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.5" } }, "nbformat": 4, "nbformat_minor": 4 }