{ "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", "## Dictionaries\n", "\n", "A *dictionary* is another builtin datatype. Unlike lists or tuples, which are indexed by a range of numbers, dictionaries are indexed by *keys* , which can be any immutable type. Strings and numbers can always be keys. Dictionaries are sometimes called \"associative arrays\" in other programming languages.\n", "\n", "There are several ways to define dictionaries. Below are three different methods." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{1: 37, 'x': 9, 17: 'a'}" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d = {1:37, 17:'a', 'x':9}\n", "d" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{1: 37, 'x': 9, 17: 'a'}" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d = dict([(1,37), (17,'a'), ('x',9)])\n", "d" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If all the keys are strings, then the following shorthand is sometimes useful:" ] }, { "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": "markdown", "metadata": {}, "source": [ "Dictionaries behave as lists, tuples, and strings for several important operations.\n", "\n", ">
Operation | \n", ">Syntax for lists | \n", ">Syntax for dictionaies | \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",
">