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