forked from ninas/umonya_notes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdictionaries.html
355 lines (283 loc) · 12.1 KB
/
dictionaries.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Introductory Programming in Python: Dictionaries</title>
<link rel='stylesheet' type='text/css' href='style.css' />
<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
<script src="animation.js" type="text/javascript">
</script>
</head>
<body onload="animate_loop()">
<div class="page">
<h1>Introductory Programming in Python: Lesson 11<br />
Dictionaries</h1>
<div class="centered">
[<a href="tuples.html">Prev: Tuples</a>] [<a href="index.html">Course Outline</a>] [<a href="strings.html">Next: Strings in Depth</a>]
</div>
<h2>What are dictionaries</h2>
<p>Dictionaries in python are known in other languages by other names,
including "associative arrays" and "mappings". The latter being perhaps
the more explanatory term. Dictionaries are basically a set of mappings
from a <strong>key</strong> to a <strong>value</strong>. Keys can be of
any non-mutable type, and values can be of any type including other
dictionaries, lists, or tuples. Dictionaries specify a set of key:value
pairs, such that when the dictionary is subscripted using a key it
contains, the value associated with that pair is returned.</p>
<h2>Forming a Dictionary</h2>
<p>Dictionaries are formed using curly braces (<code>{ }</code>), and
providing a comma separated list of key:value pairs between the open
and close braces.</p>
<pre class='listing'>
Python 2.6.4 (r264:75706, Dec 7 2009, 18:43:55) [MSC v.1310 32 bit (Intel)] on win32
[GCC 3.4.6 (Gentoo 3.4.6-r1, ssp-3.4.5-1.0, pie-8.7.9)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = {
... 0: "This is the value for key 0",
... 1: "This is the value for key 1",
... "3": "See how keys can also be strings",
... (4, 5): "Or even tuples",
... "and for fun": 7
... }
>>>
</pre>
<p>Here we have a new dictionary, which we have assigned to a variable
'a'. The dictionary contains five key:value pairs, each specified using
the format <code><key> : <value></code> within a comma
separated list within curly braces. Note how keys can be of multiple
different types within the same dictionary. <strong>Key order is not
guaranteed by python</strong>. Similarly values can be of any type, and
types can be mixed within one dictionary. Also note the existence of
the empty dictionary ...</p>
<pre class='listing'>
>>> b = {}
>>>
</pre>
<h2>Using Dictionaries</h2>
<p>Presumably, the first thing we would want to be able to do after
forming a dictionary is to manipulate the key:value pairs. We would
want to be able to extract individual pairs by their key name, which we
do by using the subscription operator
<code><dictionary>[<expression>]</code></p>
<pre class='listing'>
>>> a[0]
'This is the value for key 0'
>>> a["3"]
'See how keys can also be strings'
>>> a[4,5]
'Or even tuples'
>>>
</pre>
<p>In a similar way to lists we can change the contents of a
dictionary, meaning <strong>dictionaries are mutable</strong>.
Specifically, we can change the value of a certain key using the
assignment statement <code><dictionary>[<expression>] =
<expression></code>.</p>
<pre class='listing'>
>>> a["3"] = "Told you keys could also be strings"
>>> a["3"]
'Told you keys could also be strings'
>>>
</pre>
<p>Similarly, a simple assignment statement can add a new key:value
pair to a dictionary, as long as the key doesn't already exist in the
dictionary. If the key does already exist, it's value is simply changed
as in the assignment statement above.</p>
<pre class='listing'>
>>> a["new"] = "a new pair has been added"
>>> a
{0: 'This is the value for key 0', 1: 'This is the value for key 1', '3': 'Told
you keys could also be strings', 'new': 'a new pair has been added', (4, 5): 'Or
even tuples'}
>>>
</pre>
<p>It is important to realise, that this implicit replacement of the
values of already extant keys ensures that keys are unique. Also, note
that attempting to access a key that doesn't exist causes an
error...</p>
<pre class='listing'>
>>> a[3]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
KeyError: 3
>>>
</pre>
<p>Which means that before we can add to the value of a particular key
using an assignment such as<br /> <code>a["n"] = a["n"] + 1</code> we
must first ensure the key exists to add to. The same is of course true
of any operator applied to a key's value. The reason for this is that
assignments evaluate the expression on the right of the equals before
assigning it to the variable on the left, meaning the value of a["n"]
would be looked up before it has been put into the dictionary, causing
an error.</p>
<p>Entire dictionaries can be compared using the standard comparison
operators. If 'a' and 'b' are both dictionaries</p>
<ul>
<li><code>a == b</code> yields Equivalence. True only if both
'a'and 'b' contain exactly the same set of key:value pairs.</li>
<li><code>a < b</code>, <code>a <= b</code> yield Less
Than<br /> Since the order of the keys in a dictionary are not
guaranteed, I'm not sure how this is useful, or how the comparison
is done. Suffice it to say it is possible, but I've never seen it
used.</li>
<li><code>a > b</code>, <code>a >= b</code> yield Greater
Than<br /> See 'Less Than'</li>
<li><code>a is b</code> is True only if 'a' and 'b' are synonyms
for the same dictionary.</li>
</ul>
<p>We can loop over the keys of a dictionary, using a for
statement.</p>
<pre class='listing'>
>>> for k in a:
... print k
...
0
1
3
new
(4, 5)
>>>
</pre>
<p>Or perhaps more usefully, we can loop over the keys, and use them as
indexes into the dictionary.</p>
<pre class='listing'>
>>> for k in a:
... print k, ":", a[k]
...
0 : This is the value for key 0
1 : This is the value for key 1
3 : Told you keys could also be strings
new : a new pair has been added
(4, 5) : Or even tuples
>>>
</pre>
<p>Finally, we can extract various structures from a dictionary in the
form of lists.</p>
<ul>
<li>
<code><dictionary>.values()</code> returns a list
containing all values in the dictionary. The order of these
values is not guaranteed.
<pre class='listing'>
>>> a.values()
['This is the value for key 0', 'This is the value for key 1', 'Told you keys
could also be strings', 'a new pair has been added', 'Or even tuples']
>>>
</pre>
</li>
<li>
<code><dictionary>.keys()</code> returns a list
containing all keys in the dictionary. The order of these keys
is not guaranteed.
<pre class='listing'>
>>> a.keys()
[0, 1, '3', 'new', (4, 5)]
>>>
</pre>
</li>
<li>
<code><dictionary>.items()</code> returns a list
containing tuples of all key:value pairs in the dictionary,
where key is the first element of the tuple, and value the
second. The order of these pairs is not guaranteed.
<pre class='listing'>
>>> a.items()
[(0, 'This is the value for key 0'), (1, 'This is the value for key 1'), ('3',
'Told you keys could also be strings'), ('new', 'a new pair has been added'),
((4, 5), 'Or even tuples')]
>>>
</pre>
</li>
</ul>
<h2>Exercises</h2>
<p>Given the code:</p>
<pre class='listing'>
d = {
"fruits": ["apples", "oranges", "pears", "mangoes"],
"vegetables": ["tomatoes", "lettuce", "spinach", "green peppers"],
"meat": ["chicken", "fish", "beef", "ostrich"],
"dairy": ["yogurt", "milk", "cheese", "ice-cream"]
}</pre>
<ol>
<li>How many keys does <em>d</em> have?</li>
<li>How many values does <em>d</em> have?</li>
<li>What is the value of <code>d["meat"]</code>?</li>
<li>What is the value of <code>d["dairy"][2]</code>?</li>
<li>How do you access "spinach" using the dictionary <em>d</em>?</li>
<li>How do you add a new fruit?</li>
<li>Consider the set of key:value pairs?
<ul>
<li>"Hitchhiker's Guide to the Galaxy": 1</li>
<li>"The Restaurant at the End of the Universe": 2</li>
<li>"Life, the Universe, and Everything": 3</li>
<li>"So Long, and Thanks for all the Fish!": 4</li>
<li>"Mostly Harmless": 5</li>
</ul>
<ol>
<li>How do you create this set as a dictionary in
python?</li>
<li>How do you find which book in the 'trilogy', i.e. what
number, "The Restaurant at the End of the Universe"
is?</li>
<li>Write a program that starts by declaring the above
dictionary as a literal, and outputs the books in
order.</li>
<li>Write a program that starts by declaring the above
dictionary as a literal, and then asks the user for a
number, and prints out name of the book which has the given
number.</li>
<li>Write a program the starts by declaring the above
dictionary as a literal, then proceeds to switch the keys
and values, so that values become keys, and <i>vice
versa</i>. Print out the resulting dictionary</li>
</ol>
</li>
<li>Write a program that reads in names until a blank line is
entered, and prints out each unique name and the number of times
it was entered.</li>
<li>Write a program the reads strings until a blank line is
encountered. For each string entered, treat the portion of the
string up to the first colon (or the entire string if no colon is
present) as a key name, and everything after the first colon as a
value. If the key portion has been entered before, print out the old
value paired with that key, and then change the value to the newly
entered one. After the blank line, print out a neat list of key
value pairs.</li>
<li>A small arts and crafts store owner in the middle of the Karoo
has recently upgraded to a computerised point of sale system, and
wants to do the same for his guest book. Customers have previously
left their names a small paragraph of comment in the book. The owner
would like his customers to be able to walk up to a computer near
the exit, type in their names, and enter a brief comment. He's only
interested in a customer's most recent comments, and doesn't want
store old comments. So repeat customer's must be able to update
their previous comments. When a repeat customer types in their name,
their previous comment is displayed back to them, and they are
afforded the opportunity to enter a new comment. Should they enter a
blank line instead of a comment, their previous comment is
preserved. Also, if instead of a customer name the special command
'quit' is entered, the program exits. Similarly the command
'showcomments' causes all customers' names to be displayed, followed
by their comments slightly indented. Customer's must be able to
enter their names in a case insensitive manner.</li>
<li>Extend your solution to the previous problem, by allowing
customers to enter multi-line comments, and to terminate their
comments by entering a blank line. If the comment is entirely
blank, i.e. the first line is blank, then it does not overwrite the
former comment if any. Also, ensure that when the comments are
outputted back, either because of the 'showcomments' command, or a
repeat customer entering their name, that the line width of the
outputted comments does not exceed 60 characters, nor break a word
in two, i.e. lines are only broken on white space.</li>
<li>What happens if you make an element of a dictionary point to
itself.</li>
</ol>
<div class="centered">
[<a href="tuples.html">Prev: Tuples</a>] [<a href="index.html">Course Outline</a>] [<a href="strings.html">Next: Strings in Depth</a>]
</div>
</div>
<div class="pagefooter">
Copyright © James Dominy 2007-2008; Released under the <a href="http://www.gnu.org/copyleft/fdl.html">GNU Free Documentation License</a><br />
<a href="intropython.tar.gz">Download the tarball</a>
</div>
</body>
</html>