web/html/ch4strings_dicts.html~
changeset 0 8083d21c0020
equal deleted inserted replaced
-1:000000000000 0:8083d21c0020
       
     1 <html>
       
     2 <head>
       
     3 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
       
     4 <title>Chapter 4. strings_dicts</title>
       
     5 <link rel="stylesheet" href="/support/styles.css" type="text/css">
       
     6 <meta name="generator" content="DocBook XSL Stylesheets V1.74.3">
       
     7 <link rel="shortcut icon" type="image/png" href="/support/figs/favicon.png">
       
     8 <script type="text/javascript" src="/support/jquery-min.js"></script>
       
     9 <script type="text/javascript" src="/support/form.js"></script>
       
    10 <script type="text/javascript" src="/support/hsbook.js"></script>
       
    11 <meta name="generator" content="DocBook XSL Stylesheets V1.75.1">
       
    12 </head>
       
    13 <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"><div class="chapter" id="ch4strings_dicts">
       
    14 <div class="titlepage"></div>
       
    15 <div class="toc">
       
    16 <p><b>Table of Contents</b></p>
       
    17 <dl>
       
    18 <dt><span class="article"><a href="#id2983496">Strings</a></span></dt>
       
    19 <dd><dl>
       
    20 <dt><span class="section"><a href="#id2982083">1. String Formatting</a></span></dt>
       
    21 <dt><span class="section"><a href="#id3034500">2. String Methods</a></span></dt>
       
    22 <dd><dl>
       
    23 <dt><span class="section"><a href="#id3034515">2.1. <span class="strong"><strong>find</strong></span></a></span></dt>
       
    24 <dt><span class="section"><a href="#id3034545">2.2. <span class="strong"><strong>join</strong></span></a></span></dt>
       
    25 <dt><span class="section"><a href="#id3034585">2.3. <span class="strong"><strong>lower</strong></span></a></span></dt>
       
    26 <dt><span class="section"><a href="#id3034615">2.4. <span class="strong"><strong>replace</strong></span></a></span></dt>
       
    27 <dt><span class="section"><a href="#id3034672">2.5. <span class="strong"><strong>split</strong></span></a></span></dt>
       
    28 <dt><span class="section"><a href="#id3034731">2.6. <span class="strong"><strong>strip</strong></span></a></span></dt>
       
    29 </dl></dd>
       
    30 <dt><span class="section"><a href="#id3034775">3. Introduction to the standard library</a></span></dt>
       
    31 <dt><span class="section"><a href="#id3034853">4. I/O: Reading and Writing Files</a></span></dt>
       
    32 <dd><dl>
       
    33 <dt><span class="section"><a href="#id3034883">4.1. Opening Files</a></span></dt>
       
    34 <dt><span class="section"><a href="#id3035057">4.2. Reading and Writing files</a></span></dt>
       
    35 </dl></dd>
       
    36 <dt><span class="section"><a href="#id3035222">5. Dictionaries</a></span></dt>
       
    37 <dd><dl>
       
    38 <dt><span class="section"><a href="#id3035278">5.1. <span class="strong"><strong>dict()</strong></span></a></span></dt>
       
    39 <dt><span class="section"><a href="#id3035342">5.2. Dictionary Methods</a></span></dt>
       
    40 </dl></dd>
       
    41 </dl></dd>
       
    42 </dl>
       
    43 </div>
       
    44 <div class="article" title="Strings">
       
    45 <div class="titlepage">
       
    46 <div><div><h2 class="title">
       
    47 <a name="id2983496"></a>Strings</h2></div></div>
       
    48 <hr>
       
    49 </div>
       
    50 <div class="toc">
       
    51 <p><b>Table of Contents</b></p>
       
    52 <dl>
       
    53 <dt><span class="section"><a href="#id2982083">1. String Formatting</a></span></dt>
       
    54 <dt><span class="section"><a href="#id3034500">2. String Methods</a></span></dt>
       
    55 <dd><dl>
       
    56 <dt><span class="section"><a href="#id3034515">2.1. <span class="strong"><strong>find</strong></span></a></span></dt>
       
    57 <dt><span class="section"><a href="#id3034545">2.2. <span class="strong"><strong>join</strong></span></a></span></dt>
       
    58 <dt><span class="section"><a href="#id3034585">2.3. <span class="strong"><strong>lower</strong></span></a></span></dt>
       
    59 <dt><span class="section"><a href="#id3034615">2.4. <span class="strong"><strong>replace</strong></span></a></span></dt>
       
    60 <dt><span class="section"><a href="#id3034672">2.5. <span class="strong"><strong>split</strong></span></a></span></dt>
       
    61 <dt><span class="section"><a href="#id3034731">2.6. <span class="strong"><strong>strip</strong></span></a></span></dt>
       
    62 </dl></dd>
       
    63 <dt><span class="section"><a href="#id3034775">3. Introduction to the standard library</a></span></dt>
       
    64 <dt><span class="section"><a href="#id3034853">4. I/O: Reading and Writing Files</a></span></dt>
       
    65 <dd><dl>
       
    66 <dt><span class="section"><a href="#id3034883">4.1. Opening Files</a></span></dt>
       
    67 <dt><span class="section"><a href="#id3035057">4.2. Reading and Writing files</a></span></dt>
       
    68 </dl></dd>
       
    69 <dt><span class="section"><a href="#id3035222">5. Dictionaries</a></span></dt>
       
    70 <dd><dl>
       
    71 <dt><span class="section"><a href="#id3035278">5.1. <span class="strong"><strong>dict()</strong></span></a></span></dt>
       
    72 <dt><span class="section"><a href="#id3035342">5.2. Dictionary Methods</a></span></dt>
       
    73 </dl></dd>
       
    74 </dl>
       
    75 </div>
       
    76 <p id="ch4strings_dicts_1"></a>Strings were briefly introduced previously in the introduction document. In this
       
    77 section strings will be presented in greater detail. All the standard operations
       
    78 that can be performed on sequences such as indexing, slicing, multiplication, length
       
    79 minimum and maximum can be performed on string variables as well. One thing to
       
    80 be noted is that strings are immutable, which means that string variables are
       
    81 unchangeable. Hence, all item and slice assignments on strings are illegal.
       
    82 Let us look at a few example.</p>
       
    83 <pre class="programlisting"> &gt;&gt;&gt; name = 'PythonFreak'
       
    84 &gt;&gt;&gt; print name[3]
       
    85 h
       
    86 &gt;&gt;&gt; print name[-1]
       
    87 k
       
    88 &gt;&gt;&gt; print name[6:]
       
    89 Freak
       
    90 &gt;&gt;&gt; name[6:0] = 'Maniac'
       
    91 Traceback (most recent call last):
       
    92   File "&lt;stdin&gt;", line 1, in &lt;module&gt;
       
    93 TypeError: 'str' object does not support item assignment</pre>
       
    94 <p id="ch4strings_dicts_2"></a>This is quite expected, since string objects are immutable as already mentioned.
       
    95 The error message is clear in mentioning that 'str' object does not support item
       
    96 assignment.</p>
       
    97 <div class="section" title="1. String Formatting">
       
    98 <div class="titlepage"><div><div><h2 class="title" style="clear: both">
       
    99 <a name="id2982083"></a>1. String Formatting</h2></div></div></div>
       
   100 <p id="ch4strings_dicts_3"></a>String formatting can be performed using the string formatting operator represented
       
   101 as the percent (%) sign. The string placed before the % sign is formatted with
       
   102 the value placed to the right of it. Let us look at a simple example.</p>
       
   103 <pre class="programlisting"> &gt;&gt;&gt; format = 'Hello %s, from PythonFreak'
       
   104 &gt;&gt;&gt; str1 = 'world!'
       
   105 &gt;&gt;&gt; print format % str1
       
   106 Hello world!, from PythonFreak</pre>
       
   107 <p id="ch4strings_dicts_4"></a>The %s parts of the format string are called the coversion specifiers. The coversion
       
   108 specifiers mark the places where the formatting has to be performed in a string.
       
   109 In the example the %s is replaced by the value of str1. More than one value can
       
   110 also be formatted at a time by specifying the values to be formatted using tuples
       
   111 and dictionaries (explained in later sections). Let us look at an example.</p>
       
   112 <pre class="programlisting"> &gt;&gt;&gt; format = 'Hello %s, from %s'
       
   113 &gt;&gt;&gt; values = ('world!', 'PythonFreak')
       
   114 &gt;&gt;&gt; print format % values
       
   115 Hello world!, from PythonFreak</pre>
       
   116 <p id="ch4strings_dicts_5"></a>In this example it can be observed that the format string contains two conversion
       
   117 specifiers and they are formatted using the tuple of values as shown.</p>
       
   118 <p id="ch4strings_dicts_6"></a>The s in %s specifies that the value to be replaced is of type string. Values of
       
   119 other types can be specified as well such as integers and floats. Integers are
       
   120 specified as %d and floats as %f. The precision with which the integer or the
       
   121 float values are to be represented can also be specified using a <span class="strong"><strong>.</strong></span> (<span class="strong"><strong>dot</strong></span>)
       
   122 followed by the precision value.</p>
       
   123 </div>
       
   124 <div class="section" title="2. String Methods">
       
   125 <div class="titlepage"><div><div><h2 class="title" style="clear: both">
       
   126 <a name="id3034500"></a>2. String Methods</h2></div></div></div>
       
   127 <p id="ch4strings_dicts_7"></a>Similar to list methods, strings also have a rich set of methods to perform various
       
   128 operations on strings. Some of the most important and popular ones are presented
       
   129 in this section.</p>
       
   130 <div class="section" title="2.1. find">
       
   131 <div class="titlepage"><div><div><h3 class="title">
       
   132 <a name="id3034515"></a>2.1. <span class="strong"><strong>find</strong></span>
       
   133 </h3></div></div></div>
       
   134 <p id="ch4strings_dicts_8"></a>The <span class="strong"><strong>find</strong></span> method is used to search for a substring within a given string. It
       
   135 returns the left most index of the first occurence of the substring. If the
       
   136 substring is not found in the string then it returns -1. Let us look at a few
       
   137 examples.</p>
       
   138 <pre class="programlisting"> &gt;&gt;&gt; longstring = 'Hello world!, from PythonFreak'
       
   139 &gt;&gt;&gt; longstring.find('Python')
       
   140 19
       
   141 &gt;&gt;&gt; longstring.find('Perl')
       
   142 -1</pre>
       
   143 </div>
       
   144 <div class="section" title="2.2. join">
       
   145 <div class="titlepage"><div><div><h3 class="title">
       
   146 <a name="id3034545"></a>2.2. <span class="strong"><strong>join</strong></span>
       
   147 </h3></div></div></div>
       
   148 <p id="ch4strings_dicts_9"></a>The <span class="strong"><strong>join</strong></span> method is used to join the elements of a sequence. The sequence
       
   149 elements that are to be join ed should all be strings. Let us look at a few
       
   150 examples.</p>
       
   151 <pre class="programlisting"> &gt;&gt;&gt; seq = ['With', 'great', 'power', 'comes', 'great', 'responsibility']
       
   152 &gt;&gt;&gt; sep = ' '
       
   153 &gt;&gt;&gt; sep.join(seq)
       
   154 'With great power comes great responsibility'
       
   155 &gt;&gt;&gt; sep = ',!'
       
   156 &gt;&gt;&gt; sep.join(seq)
       
   157 'With,!great,!power,!comes,!great,!responsibility'</pre>
       
   158 <p id="ch4strings_dicts_a"></a><span class="emphasis"><em>Try this yourself</em></span></p>
       
   159 <pre class="programlisting"> &gt;&gt;&gt; seq = [12,34,56,78]
       
   160 &gt;&gt;&gt; sep.join(seq)</pre>
       
   161 </div>
       
   162 <div class="section" title="2.3. lower">
       
   163 <div class="titlepage"><div><div><h3 class="title">
       
   164 <a name="id3034585"></a>2.3. <span class="strong"><strong>lower</strong></span>
       
   165 </h3></div></div></div>
       
   166 <p id="ch4strings_dicts_b"></a>The <span class="strong"><strong>lower</strong></span> method, as the name indicates, converts the entire text of a string
       
   167 to lower case. It is specially useful in cases where the programmers deal with case
       
   168 insensitive data. Let us look at a few examples.</p>
       
   169 <pre class="programlisting"> &gt;&gt;&gt; sometext = 'Hello world!, from PythonFreak'
       
   170 &gt;&gt;&gt; sometext.lower()
       
   171 'hello world!, from pythonfreak'</pre>
       
   172 </div>
       
   173 <div class="section" title="2.4. replace">
       
   174 <div class="titlepage"><div><div><h3 class="title">
       
   175 <a name="id3034615"></a>2.4. <span class="strong"><strong>replace</strong></span>
       
   176 </h3></div></div></div>
       
   177 <p id="ch4strings_dicts_c"></a>The <span class="strong"><strong>replace</strong></span> method replaces a substring with another substring within
       
   178 a given string and returns the new string. Let us look at an example.</p>
       
   179 <pre class="programlisting"> &gt;&gt;&gt; sometext = 'Concise, precise and criticise is some of the words that end with ise'
       
   180 &gt;&gt;&gt; sometext.replace('is', 'are')
       
   181 'Concaree, precaree and criticaree are some of the words that end with aree'</pre>
       
   182 <p id="ch4strings_dicts_d"></a>Observe here that all the occurences of the substring <span class="emphasis"><em>is</em></span> have been replaced,
       
   183 even the <span class="emphasis"><em>is</em></span> in <span class="emphasis"><em>concise</em></span>, <span class="emphasis"><em>precise</em></span> and <span class="emphasis"><em>criticise</em></span> have been replaced.</p>
       
   184 </div>
       
   185 <div class="section" title="2.5. split">
       
   186 <div class="titlepage"><div><div><h3 class="title">
       
   187 <a name="id3034672"></a>2.5. <span class="strong"><strong>split</strong></span>
       
   188 </h3></div></div></div>
       
   189 <p id="ch4strings_dicts_e"></a>The <span class="strong"><strong>split</strong></span> is one of the very important string methods. split is the opposite of the
       
   190 <span class="strong"><strong>join</strong></span> method. It is used to split a string based on the argument passed as the
       
   191 delimiter. It returns a list of strings. By default when no argument is passed it
       
   192 splits with <span class="emphasis"><em>space</em></span> (' ') as the delimiter. Let us look at an example.</p>
       
   193 <pre class="programlisting"> &gt;&gt;&gt; grocerylist = 'butter, cucumber, beer(a grocery item??), wheatbread'
       
   194 &gt;&gt;&gt; grocerylist.split(',')
       
   195 ['butter', ' cucumber', ' beer(a grocery item??)', ' wheatbread']
       
   196 &gt;&gt;&gt; grocerylist.split()
       
   197 ['butter,', 'cucumber,', 'beer(a', 'grocery', 'item??),', 'wheatbread']</pre>
       
   198 <p id="ch4strings_dicts_f"></a>Observe here that in the second case when the delimiter argument was not set
       
   199 <span class="strong"><strong>split</strong></span> was done with <span class="emphasis"><em>space</em></span> as the delimiter.</p>
       
   200 </div>
       
   201 <div class="section" title="2.6. strip">
       
   202 <div class="titlepage"><div><div><h3 class="title">
       
   203 <a name="id3034731"></a>2.6. <span class="strong"><strong>strip</strong></span>
       
   204 </h3></div></div></div>
       
   205 <p id="ch4strings_dicts_10"></a>The <span class="strong"><strong>strip</strong></span> method is used to remove or <span class="strong"><strong>strip</strong></span> off any whitespaces that exist
       
   206 to the left and right of a string, but not the whitespaces within a string. Let
       
   207 us look at an example.</p>
       
   208 <pre class="programlisting"> &gt;&gt;&gt; spacedtext = "               Where's the text??                 "
       
   209 &gt;&gt;&gt; spacedtext.strip()
       
   210 "Where's the text??"</pre>
       
   211 <p id="ch4strings_dicts_11"></a>Observe that the whitespaces between the words have not been removed.</p>
       
   212 <pre class="programlisting"> Note: Very important thing to note is that all the methods shown above do not
       
   213       transform the source string. The source string still remains the same.
       
   214       Remember that **strings are immutable**.</pre>
       
   215 </div>
       
   216 </div>
       
   217 <div class="section" title="3. Introduction to the standard library">
       
   218 <div class="titlepage"><div><div><h2 class="title" style="clear: both">
       
   219 <a name="id3034775"></a>3. Introduction to the standard library</h2></div></div></div>
       
   220 <p id="ch4strings_dicts_12"></a>Python is often referred to as a "Batteries included!" language, mainly because
       
   221 of the Python Standard Library. The Python Standard Library provides an extensive
       
   222 set of features some of which are available directly for use while some require to
       
   223 import a few <span class="strong"><strong>modules</strong></span>. The Standard Library provides various built-in functions
       
   224 like:</p>
       
   225 <span style="color: black"><span style="color: black"><span style="color: black"><p id="ch4strings_dicts_13"></a><span class="strong"><strong>abs()</strong></span></p></span><span style="color: black"><p id="ch4strings_dicts_14"></a><span class="strong"><strong>dict()</strong></span></p></span><span style="color: black"><p id="ch4strings_dicts_15"></a><span class="strong"><strong>enumerate()</strong></span></p></span></span></span><p id="ch4strings_dicts_16"></a>The built-in constants like <span class="strong"><strong>True</strong></span> and <span class="strong"><strong>False</strong></span> are provided by the Standard Library.
       
   226 More information about the Python Standard Library is available </p>
       
   227 <div class="reference">
       
   228 <div class="titlepage"><hr></div>http://docs.python.org/library/</div>
       
   229 </div>
       
   230 <div class="section" title="4. I/O: Reading and Writing Files">
       
   231 <div class="titlepage"><div><div><h2 class="title" style="clear: both">
       
   232 <a name="id3034853"></a>4. I/O: Reading and Writing Files</h2></div></div></div>
       
   233 <p id="ch4strings_dicts_17"></a>Files are very important aspects when it comes to computing and programming.
       
   234 Up until now the focus has been on small programs that interacted with users
       
   235 through <span class="strong"><strong>input()</strong></span> and <span class="strong"><strong>raw_input()</strong></span>. Generally, for computational purposes
       
   236 it becomes necessary to handle files, which are usually large in size as well.
       
   237 This section focuses on basics of file handling.</p>
       
   238 <div class="section" title="4.1. Opening Files">
       
   239 <div class="titlepage"><div><div><h3 class="title">
       
   240 <a name="id3034883"></a>4.1. Opening Files</h3></div></div></div>
       
   241 <p id="ch4strings_dicts_18"></a>Files can be opened using the <span class="strong"><strong>open()</strong></span> method. <span class="strong"><strong>open()</strong></span> accepts 3 arguments
       
   242 out of which 2 are optional. Let us look at the syntax of <span class="strong"><strong>open()</strong></span>:</p>
       
   243 <p id="ch4strings_dicts_19"></a><span class="emphasis"><em>f = open( filename, mode, buffering)</em></span></p>
       
   244 <p id="ch4strings_dicts_1a"></a>The <span class="emphasis"><em>filename</em></span> is a compulsory argument while the <span class="emphasis"><em>mode</em></span> and <span class="emphasis"><em>buffering</em></span> are
       
   245 optional. The <span class="emphasis"><em>filename</em></span> should be a string and it should be the complete path
       
   246 to the file to be opened (The path can be absolute or relative). Let us look at
       
   247 an example.</p>
       
   248 <pre class="programlisting"> &gt;&gt;&gt; f = open ('basic_python/interim_assessment.rst')</pre>
       
   249 <p id="ch4strings_dicts_1b"></a>The <span class="emphasis"><em>mode</em></span> argument specifies the mode in which the file has to be opened.
       
   250 The following are the valid mode arguments:</p>
       
   251 <p id="ch4strings_dicts_1c"></a><span class="strong"><strong>r</strong></span> - Read mode
       
   252 <span class="strong"><strong>w</strong></span> - Write mode
       
   253 <span class="strong"><strong>a</strong></span> - Append mode
       
   254 <span class="strong"><strong>b</strong></span> - Binary mode
       
   255 <span class="strong"><strong>+</strong></span> - Read/Write mode</p>
       
   256 <p id="ch4strings_dicts_1d"></a>The read mode opens the file as a read-only document. The write mode opens the
       
   257 file in the Write only mode. In the write mode, if the file existed prior to the
       
   258 opening, the previous contents of the file are erased. The append mode opens the
       
   259 file in the write mode but the previous contents of the file are not erased and
       
   260 the current data is appended onto the file.
       
   261 The binary and the read/write modes are special in the sense that they are added
       
   262 onto other modes. The read/write mode opens the file in the reading and writing
       
   263 mode combined. The binary mode can be used to open a files that do not contain
       
   264 text. Binary files such as images should be opened in the binary mode. Let us look
       
   265 at a few examples.</p>
       
   266 <pre class="programlisting"> &gt;&gt;&gt; f = open ('basic_python/interim_assessment.rst', 'r')
       
   267 &gt;&gt;&gt; f = open ('armstrong.py', 'r+')</pre>
       
   268 <p id="ch4strings_dicts_1e"></a>The third argument to the <span class="strong"><strong>open()</strong></span> method is the <span class="emphasis"><em>buffering</em></span> argument. This takes
       
   269 a boolean value, <span class="emphasis"><em>True</em></span> or <span class="emphasis"><em>1</em></span> indicates that buffering has to be enabled on the file,
       
   270 that is the file is loaded on to the main memory and the changes made to the file are
       
   271 not immediately written to the disk. If the <span class="emphasis"><em>buffering</em></span> argument is <span class="emphasis"><em>0</em></span> or <span class="emphasis"><em>False</em></span> the
       
   272 changes are directly written on to the disk immediately.</p>
       
   273 </div>
       
   274 <div class="section" title="4.2. Reading and Writing files">
       
   275 <div class="titlepage"><div><div><h3 class="title">
       
   276 <a name="id3035057"></a>4.2. Reading and Writing files</h3></div></div></div>
       
   277 <div class="section" title="4.2.1. write()">
       
   278 <div class="titlepage"><div><div><h4 class="title">
       
   279 <a name="id3035066"></a>4.2.1. <span class="strong"><strong>write()</strong></span>
       
   280 </h4></div></div></div>
       
   281 <p id="ch4strings_dicts_1f"></a><span class="strong"><strong>write()</strong></span>, evidently, is used to write data onto a file. It takes the data to
       
   282 be written as the argument. The data can be a string, an integer, a float or any
       
   283 other datatype. In order to be able to write data onto a file, the file has to
       
   284 be opened in one of <span class="strong"><strong>w</strong></span>, <span class="strong"><strong>a</strong></span> or <span class="strong"><strong>+</strong></span> modes.</p>
       
   285 </div>
       
   286 <div class="section" title="4.2.2. read()">
       
   287 <div class="titlepage"><div><div><h4 class="title">
       
   288 <a name="id3035105"></a>4.2.2. <span class="strong"><strong>read()</strong></span>
       
   289 </h4></div></div></div>
       
   290 <p id="ch4strings_dicts_20"></a><span class="strong"><strong>read()</strong></span> is used to read data from a file. It takes the number of bytes of data
       
   291 to be read as the argument. If nothing is specified by default it reads the entire
       
   292 contents from the current position to the end of file.</p>
       
   293 <p id="ch4strings_dicts_21"></a>Let us look at a few examples:</p>
       
   294 <pre class="programlisting"> &gt;&gt;&gt; f = open ('randomtextfile', 'w')
       
   295 &gt;&gt;&gt; f.write('Hello all, this is PythonFreak. This is a random text file.')
       
   296 &gt;&gt;&gt; f = open ('../randomtextfile', 'r')
       
   297 &gt;&gt;&gt; f = open ('../randomtextfile', 'r')
       
   298 &gt;&gt;&gt; f.read(5)
       
   299 'Hello'
       
   300 &gt;&gt;&gt; f.read()
       
   301 ' all, this is PythonFreak. This is a random text file.'
       
   302 &gt;&gt;&gt; f.close()</pre>
       
   303 </div>
       
   304 <div class="section" title="4.2.3. readline()">
       
   305 <div class="titlepage"><div><div><h4 class="title">
       
   306 <a name="id3035140"></a>4.2.3. <span class="strong"><strong>readline()</strong></span>
       
   307 </h4></div></div></div>
       
   308 <p id="ch4strings_dicts_22"></a><span class="strong"><strong>readline()</strong></span> is used to read a file line by line. <span class="strong"><strong>readline()</strong></span> reads a line
       
   309 of a file at a time. When an argument is passed to <span class="strong"><strong>readline()</strong></span> it reads that
       
   310 many bytes from the current line.</p>
       
   311 <p id="ch4strings_dicts_23"></a>One other method to read a file line by line is using the <span class="strong"><strong>read()</strong></span> and the
       
   312 <span class="strong"><strong>for</strong></span> construct. Let us look at this block of code as an example.</p>
       
   313 <pre class="programlisting"> &gt;&gt;&gt; f = open('../randomtextfile', 'r')
       
   314 &gt;&gt;&gt; for line in f:
       
   315 ...     print line
       
   316 ...
       
   317 Hello all!
       
   318 
       
   319 This is PythonFreak on the second line.
       
   320 
       
   321 This is a random text file on line 3</pre>
       
   322 </div>
       
   323 <div class="section" title="4.2.4. close()">
       
   324 <div class="titlepage"><div><div><h4 class="title">
       
   325 <a name="id3035199"></a>4.2.4. <span class="strong"><strong>close()</strong></span>
       
   326 </h4></div></div></div>
       
   327 <p id="ch4strings_dicts_24"></a>One must always close all the files that have been opened. Although, files opened
       
   328 will be closed automatically when the program ends. When files opened in read mode
       
   329 are not closed it might lead to uselessly locked sometimes. In case of files
       
   330 opened in the write mode it is more important to close the files. This is because,
       
   331 Python maybe using the file in the buffering mode and when the file is not closed
       
   332 the buffer maybe lost completely and the changes made to the file are lost forever.</p>
       
   333 </div>
       
   334 </div>
       
   335 </div>
       
   336 <div class="section" title="5. Dictionaries">
       
   337 <div class="titlepage"><div><div><h2 class="title" style="clear: both">
       
   338 <a name="id3035222"></a>5. Dictionaries</h2></div></div></div>
       
   339 <p id="ch4strings_dicts_25"></a>A dictionary in general, are designed to be able to look up meanings of words.
       
   340 Similarly, the Python dictionaries are also designed to look up for a specific
       
   341 key and retrieve the corresponding value. Dictionaries are data structures that
       
   342 provide key-value mappings. Dictionaries are similar to lists except that instead
       
   343 of the values having integer indexes, dictionaries have keys or strings as indexes.
       
   344 Let us look at an example of how to define dictionaries.</p>
       
   345 <pre class="programlisting"> &gt;&gt;&gt; dct = { 'Sachin': 'Tendulkar', 'Rahul': 'Dravid', 'Anil': 'Kumble'}</pre>
       
   346 <p id="ch4strings_dicts_26"></a>The dictionary consists of pairs of strings, which are called <span class="emphasis"><em>keys</em></span> and their
       
   347 corresponding <span class="emphasis"><em>values</em></span> separated by <span class="emphasis"><em>:</em></span> and each of these <span class="emphasis"><em>key-value</em></span> pairs are
       
   348 comma(',') separated and the entire structure wrapped in a pair curly braces <span class="emphasis"><em>{}</em></span>.</p>
       
   349 <pre class="programlisting"> Note: The data inside a dictionary is not ordered. The order in which you enter
       
   350 the key-value pairs is not the order in which they are stored in the dictionary.
       
   351 Python has an internal storage mechanism for that which is out of the purview
       
   352 of this document.</pre>
       
   353 <div class="section" title="5.1. dict()">
       
   354 <div class="titlepage"><div><div><h3 class="title">
       
   355 <a name="id3035278"></a>5.1. <span class="strong"><strong>dict()</strong></span>
       
   356 </h3></div></div></div>
       
   357 <p id="ch4strings_dicts_27"></a>The <span class="strong"><strong>dict()</strong></span> function is used to create dictionaries from other mappings or other
       
   358 dictionaries. Let us look at an example.</p>
       
   359 <pre class="programlisting"> &gt;&gt;&gt; diction = dict(mat = 133, avg = 52.53)</pre>
       
   360 <p id="ch4strings_dicts_28"></a><span class="strong"><strong>String Formatting with Dictionaries:</strong></span></p>
       
   361 <p id="ch4strings_dicts_29"></a>String formatting was discussed in the previous section and it was mentioned that
       
   362 dictionaries can also be used for formatting more than one value. This section
       
   363 focuses on the formatting of strings using dictionaries. String formatting using
       
   364 dictionaries is more appealing than doing the same with tuples. Here the <span class="emphasis"><em>keyword</em></span>
       
   365 can be used as a place holder and the <span class="emphasis"><em>value</em></span> corresponding to it is replaced in
       
   366 the formatted string. Let us look at an example.</p>
       
   367 <pre class="programlisting"> &gt;&gt;&gt; player = { 'Name':'Rahul Dravid', 'Matches':133, 'Avg':52.53, '100s':26 }
       
   368 &gt;&gt;&gt; strng = '%(Name)s has played %(Matches)d with an average of %(Avg).2f and has %(100s)d hundreds to his name.'
       
   369 &gt;&gt;&gt; print strng % player
       
   370 Rahul Dravid has played 133 with an average of 52.53 and has 26 hundreds to his name.</pre>
       
   371 </div>
       
   372 <div class="section" title="5.2. Dictionary Methods">
       
   373 <div class="titlepage"><div><div><h3 class="title">
       
   374 <a name="id3035342"></a>5.2. Dictionary Methods</h3></div></div></div>
       
   375 <div class="section" title="5.2.1. clear()">
       
   376 <div class="titlepage"><div><div><h4 class="title">
       
   377 <a name="id3035351"></a>5.2.1. <span class="strong"><strong>clear()</strong></span>
       
   378 </h4></div></div></div>
       
   379 <p id="ch4strings_dicts_2a"></a>The <span class="strong"><strong>clear()</strong></span> method removes all the existing <span class="emphasis"><em>key-value</em></span> pairs from a dictionary.
       
   380 It returns <span class="emphasis"><em>None</em></span> or rather does not return anything. It is a method that changes
       
   381 the object. It has to be noted here that dictionaries are not immutable. Let us
       
   382 look at an example.</p>
       
   383 <pre class="programlisting"> &gt;&gt;&gt; dct
       
   384 {'Anil': 'Kumble', 'Sachin': 'Tendulkar', 'Rahul': 'Dravid'}
       
   385 &gt;&gt;&gt; dct.clear()
       
   386 &gt;&gt;&gt; dct
       
   387 {}</pre>
       
   388 </div>
       
   389 <div class="section" title="5.2.2. copy()">
       
   390 <div class="titlepage"><div><div><h4 class="title">
       
   391 <a name="id3035386"></a>5.2.2. <span class="strong"><strong>copy()</strong></span>
       
   392 </h4></div></div></div>
       
   393 <p id="ch4strings_dicts_2b"></a>The <span class="strong"><strong>copy()</strong></span> returns a copy of a given dictionary. Let us look at an example.</p>
       
   394 <pre class="programlisting"> &gt;&gt;&gt; dct = {'Anil': 'Kumble', 'Sachin': 'Tendulkar', 'Rahul': 'Dravid'}
       
   395 &gt;&gt;&gt; dctcopy = dct.copy()
       
   396 &gt;&gt;&gt; dctcopy
       
   397 {'Anil': 'Kumble', 'Sachin': 'Tendulkar', 'Rahul': 'Dravid'}</pre>
       
   398 </div>
       
   399 <div class="section" title="5.2.3. get()">
       
   400 <div class="titlepage"><div><div><h4 class="title">
       
   401 <a name="id3035417"></a>5.2.3. <span class="strong"><strong>get()</strong></span>
       
   402 </h4></div></div></div>
       
   403 <p id="ch4strings_dicts_2c"></a><span class="strong"><strong>get()</strong></span> returns the <span class="emphasis"><em>value</em></span> for the <span class="emphasis"><em>key</em></span> passed as the argument and if the
       
   404 <span class="emphasis"><em>key</em></span> does not exist in the dictionary, it returns <span class="emphasis"><em>None</em></span>. Let us look at an
       
   405 example.</p>
       
   406 <pre class="programlisting"> &gt;&gt;&gt; print dctcopy.get('Saurav')
       
   407 None
       
   408 &gt;&gt;&gt; print dctcopy.get('Anil')
       
   409 Kumble</pre>
       
   410 </div>
       
   411 <div class="section" title="5.2.4. has_key()">
       
   412 <div class="titlepage"><div><div><h4 class="title">
       
   413 <a name="id3035455"></a>5.2.4. <span class="strong"><strong>has_key()</strong></span>
       
   414 </h4></div></div></div>
       
   415 <p id="ch4strings_dicts_2d"></a>This method returns <span class="emphasis"><em>True</em></span> if the given <span class="emphasis"><em>key</em></span> is in the dictionary, else it returns
       
   416 <span class="emphasis"><em>False</em></span>.</p>
       
   417 <pre class="programlisting"> &gt;&gt;&gt; dctcopy.has_key('Saurav')
       
   418 False
       
   419 &gt;&gt;&gt; dctcopy.has_key('Sachin')
       
   420 True</pre>
       
   421 </div>
       
   422 <div class="section" title="5.2.5. pop()">
       
   423 <div class="titlepage"><div><div><h4 class="title">
       
   424 <a name="id3035485"></a>5.2.5. <span class="strong"><strong>pop()</strong></span>
       
   425 </h4></div></div></div>
       
   426 <p id="ch4strings_dicts_2e"></a>This method is used to retrieve the <span class="emphasis"><em>value</em></span> of a given <span class="emphasis"><em>key</em></span> and subsequently
       
   427 remove the <span class="emphasis"><em>key-value</em></span> pair from the dictionary. Let us look at an example.</p>
       
   428 <pre class="programlisting"> &gt;&gt;&gt; print dctcopy.pop('Sachin')
       
   429 Tendulkar
       
   430 &gt;&gt;&gt; dctcopy
       
   431 {'Anil': 'Kumble', 'Rahul': 'Dravid'}</pre>
       
   432 </div>
       
   433 <div class="section" title="5.2.6. popitem()">
       
   434 <div class="titlepage"><div><div><h4 class="title">
       
   435 <a name="id3035519"></a>5.2.6. <span class="strong"><strong>popitem()</strong></span>
       
   436 </h4></div></div></div>
       
   437 <p id="ch4strings_dicts_2f"></a>This method randomly pops a <span class="emphasis"><em>key-value</em></span> pair from a dictionary and returns it.
       
   438 The <span class="emphasis"><em>key-value</em></span> pair returned is removed from the dictionary. Let us look at an
       
   439 example.</p>
       
   440 <pre class="programlisting"> &gt;&gt;&gt; print dctcopy.popitem()
       
   441 ('Anil', 'Kumble')
       
   442 &gt;&gt;&gt; dctcopy
       
   443 {'Rahul': 'Dravid'}
       
   444 
       
   445 Note that the item chosen is completely random since dictionaries are unordered
       
   446 as mentioned earlier.</pre>
       
   447 </div>
       
   448 <div class="section" title="5.2.7. update()">
       
   449 <div class="titlepage"><div><div><h4 class="title">
       
   450 <a name="id3035555"></a>5.2.7. <span class="strong"><strong>update()</strong></span>
       
   451 </h4></div></div></div>
       
   452 <p id="ch4strings_dicts_30"></a>The <span class="strong"><strong>update()</strong></span> method updates the contents of one dictionary with the contents
       
   453 of another dictionary. For items with existing <span class="emphasis"><em>keys</em></span> their <span class="emphasis"><em>values</em></span> are updated,
       
   454 and the rest of the items are added. Let us look at an example.</p>
       
   455 <pre class="programlisting"> &gt;&gt;&gt; dctcopy.update(dct)
       
   456 &gt;&gt;&gt; dct
       
   457 {'Anil': 'Kumble', 'Sachin': 'Tendulkar', 'Rahul': 'Dravid'}
       
   458 &gt;&gt;&gt; dctcopy
       
   459 {'Anil': 'Kumble', 'Sachin': 'Tendulkar', 'Rahul': 'Dravid'}</pre>
       
   460 </div>
       
   461 </div>
       
   462 </div>
       
   463 </div>
       
   464 </div></body>
       
   465 </html>