{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\def\\CC{\\bf C}\n", "\\def\\QQ{\\bf Q}\n", "\\def\\RR{\\bf R}\n", "\\def\\ZZ{\\bf Z}\n", "\\def\\NN{\\bf N}\n", "$$\n", "# Dictionaries and Graph Theory\n", "\n", "Authors \n", "-Franco Saliola\n", "\n", "## Dictionaries\n", "\n", "A *dictionary* is another builtin datatype. Unlike lists or tuples,\n", "which are indexed by a range of numbers, dictionaries are indexed by\n", "*keys* , which can be any immutable type. Strings and numbers can always\n", "be keys. Dictionaries are sometimes called \"associative arrays\" in other\n", "programming languages.\n", "\n", "There are several ways to define dictionaries. Below are equivalent ways\n", "to define a dictionary that pairs 'key1' with 'value1' and 'key2' with\n", "'value2'." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'key2': 'value2', 'key1': 'value1'}" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d = {'key1':'value1', 'key2':'value2'}\n", "d" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'key2': 'value2', 'key1': 'value1'}" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d = dict(key1='value1', key2='value2')\n", "d" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'key2': 'value2', 'key1': 'value1'}" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d = dict([('key1','value1'), ('key2','value2')])\n", "d" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'a': (6, 5), 1: [2, 2], 0: {1: 2}}" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d = {1:[2,2], 'a':(6,5), 0:{1:2}}\n", "d" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Dictionaries behave as lists, tuples, and strings for several important\n", "operations.\n", "\n", "
Operation | \n", "Syntax for lists | \n", "Syntax for dictionaries | \n", "
Accessing elements | \n", "L[3] | \n",
"D[3] | \n",
"
Length | \n", "len(L) | \n",
"len(D) | \n",
"
Modifying | \n", "L[3] = 17 | \n",
"D[3] = 17 | \n",
"
Deleting items | \n", "del L[3] | \n",
"del D[3] | \n",
"