{ "nbformat_minor": 2, "nbformat": 4, "cells": [ { "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", "- M\u00e9lodie Lapointe\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 equivalent ways to define a dictionary that pairs 'key1' with 'value1' and 'key2' with 'value2'." ], "cell_type": "markdown", "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "d = {'key1':'value1', 'key2':'value2'}\n", "d" ], "outputs": [ { "execution_count": 1, "output_type": "execute_result", "data": { "text/plain": [ "{'key2': 'value2', 'key1': 'value1'}" ] }, "metadata": {} } ], "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "d = dict(key1='value1', key2='value2')\n", "d" ], "outputs": [ { "execution_count": 1, "output_type": "execute_result", "data": { "text/plain": [ "{'key2': 'value2', 'key1': 'value1'}" ] }, "metadata": {} } ], "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "d = dict([('key1','value1'), ('key2','value2')])\n", "d" ], "outputs": [ { "execution_count": 1, "output_type": "execute_result", "data": { "text/plain": [ "{'key2': 'value2', 'key1': 'value1'}" ] }, "metadata": {} } ], "metadata": {} }, { "execution_count": null, "cell_type": "code", "source": [ "d = {1:[2,2], 'a':(6,5), 0:{1:2}}\n", "d" ], "outputs": [ { "execution_count": 1, "output_type": "execute_result", "data": { "text/plain": [ "{'a': (6, 5), 1: [2, 2], 0: {1: 2}}" ] }, "metadata": {} } ], "metadata": {} }, { "source": [ "Dictionaries behave as lists, tuples, and strings for several important 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", "