You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This section introduces data structures in the form of tuples and dictionaries.
6
+
3
7
### Primitive Datatypes
4
8
5
9
Python has a few primitive types of data:
@@ -16,7 +20,8 @@ We learned about these in the introduction.
16
20
email_address =None
17
21
```
18
22
19
-
This type is often used as a placeholder for optional or missing value.
23
+
`None` is often used as a placeholder for optional or missing value. It
24
+
evaluates as `False` in conditionals.
20
25
21
26
```python
22
27
if email_address:
@@ -25,8 +30,7 @@ if email_address:
25
30
26
31
### Data Structures
27
32
28
-
Real programs have more complex data than the ones that can be easily represented by the datatypes learned so far.
29
-
For example information about a stock:
33
+
Real programs have more complex data. For example information about a stock holding:
30
34
31
35
```code
32
36
100 shares of GOOG at $490.10
@@ -61,7 +65,7 @@ t = () # An empty tuple
61
65
w = ('GOOG', ) # A 1-item tuple
62
66
```
63
67
64
-
Tuples are usually used to represent *simple* records or structures.
68
+
Tuples are often used to represent *simple* records or structures.
65
69
Typically, it is a single *object* of multiple parts. A good analogy: *A tuple is like a single row in a database table.*
66
70
67
71
Tuple contents are ordered (like an array).
@@ -73,9 +77,9 @@ shares = s[1] # 100
73
77
price = s[2] # 490.1
74
78
```
75
79
76
-
However, th contents can't be modified.
80
+
However, the contents can't be modified.
77
81
78
-
```pycon
82
+
```python
79
83
>>> s[1] =75
80
84
TypeError: object does not support item assignment
81
85
```
@@ -88,7 +92,7 @@ s = (s[0], 75, s[2])
88
92
89
93
### Tuple Packing
90
94
91
-
Tuples are focused more on packing related items together into a single *entity*.
95
+
Tuples are more about packing related items together into a single *entity*.
92
96
93
97
```python
94
98
s = ('GOOG', 100, 490.1)
@@ -105,7 +109,7 @@ name, shares, price = s
105
109
print('Cost', shares * price)
106
110
```
107
111
108
-
The number of variables must match the tuple structure.
112
+
The number of variables on the left must match the tuple structure.
109
113
110
114
```python
111
115
name, shares = s # ERROR
@@ -116,19 +120,20 @@ ValueError: too many values to unpack
116
120
117
121
### Tuples vs. Lists
118
122
119
-
Tuples are NOT just read-only lists. Tuples are most ofter used for a *single item* consisting of multiple parts.
120
-
Lists are usually a collection of distinct items, usually all of the same type.
123
+
Tuples look like read-only lists. However, tuples are most often used
124
+
for a *single item* consisting of multiple parts. Lists are usually a
125
+
collection of distinct items, usually all of the same type.
121
126
122
127
```python
123
-
record = ('GOOG', 100, 490.1) # A tuple representing a stock in a portfolio
128
+
record = ('GOOG', 100, 490.1) # A tuple representing a record in a portfolio
124
129
125
130
symbols = [ 'GOOG', 'AAPL', 'IBM' ] # A List representing three stock symbols
126
131
```
127
132
128
133
### Dictionaries
129
134
130
-
A dictionary is a hash table or associative array.
131
-
It is a collection of values indexed by *keys*. These keys serve as field names.
135
+
A dictionary is mapping of keys to values. It's also sometimes called a hash table or
136
+
associative array. The keysserve as indices for accessing values.
132
137
133
138
```python
134
139
s = {
@@ -140,9 +145,9 @@ s = {
140
145
141
146
### Common operations
142
147
143
-
To read values from a dictionary use the key names.
148
+
To get values from a dictionary use the key names.
144
149
145
-
```pycon
150
+
```python
146
151
>>>print(s['name'], s['shares'])
147
152
GOOG100
148
153
>>> s['price']
@@ -152,15 +157,15 @@ GOOG 100
152
157
153
158
To add or modify values assign using the key names.
154
159
155
-
```pycon
160
+
```python
156
161
>>> s['shares'] =75
157
162
>>> s['date'] ='6/6/2007'
158
163
>>>
159
164
```
160
165
161
166
To delete a value use the `del` statement.
162
167
163
-
```pycon
168
+
```python
164
169
>>>del s['date']
165
170
>>>
166
171
```
@@ -178,11 +183,11 @@ s[2]
178
183
179
184
## Exercises
180
185
181
-
### Note
186
+
In the last few exercises, you wrote a program that read a datafile
187
+
`Data/portfolio.csv`. Using the `csv` module, it is easy to read the
188
+
file row-by-row.
182
189
183
-
In the last few exercises, you wrote a program that read a datafile `Data/portfolio.csv`. Using the `csv` module, it is easy to read the file row-by-row.
184
-
185
-
```pycon
190
+
```python
186
191
>>>import csv
187
192
>>> f =open('Data/portfolio.csv')
188
193
>>> rows = csv.reader(f)
@@ -194,11 +199,13 @@ In the last few exercises, you wrote a program that read a datafile `Data/portfo
194
199
>>>
195
200
```
196
201
197
-
Although reading the file is easy, you often want to do more with the data than read it.
198
-
For instance, perhaps you want to store it and start performing some calculations on it.
199
-
Unfortunately, a raw "row" of data doesn’t give you enough to work with. For example, even a simple math calculation doesn’t work:
202
+
Although reading the file is easy, you often want to do more with the
203
+
data than read it. For instance, perhaps you want to store it and
204
+
start performing some calculations on it. Unfortunately, a raw "row"
205
+
of data doesn’t give you enough to work with. For example, even a
206
+
simple math calculation doesn’t work:
200
207
201
-
```pycon
208
+
```python
202
209
>>> row = ['AA', '100', '32.20']
203
210
>>> cost = row[1] * row[2]
204
211
Traceback (most recent call last):
@@ -207,25 +214,27 @@ TypeError: can't multiply sequence by non-int of type 'str'
207
214
>>>
208
215
```
209
216
210
-
To do more, you typically want to interpret the raw data in some way and turn it into a more useful kind of object so that you can work with it later.
211
-
Two simple options are tuples or dictionaries.
217
+
To do more, you typically want to interpret the raw data in some way
218
+
and turn it into a more useful kind of object so that you can work
219
+
with it later. Two simple options are tuples or dictionaries.
212
220
213
221
### Exercise 2.1: Tuples
214
222
215
223
At the interactive prompt, create the following tuple that represents
216
224
the above row, but with the numeric columns converted to proper
217
225
numbers:
218
226
219
-
```pycon
227
+
```python
220
228
>>> t = (row[0], int(row[1]), float(row[2]))
221
229
>>> t
222
230
('AA', 100, 32.2)
223
231
>>>
224
232
```
225
233
226
-
Using this, you can now calculate the total cost by multiplying the shares and the price:
234
+
Using this, you can now calculate the total cost by multiplying the
235
+
shares and the price:
227
236
228
-
```pycon
237
+
```python
229
238
>>> cost = t[1] * t[2]
230
239
>>> cost
231
240
3220.0000000000005
@@ -244,25 +253,27 @@ surprising if you haven’t seen it before.
244
253
This happens in all programming languages that use floating point
245
254
decimals, but it often gets hidden when printing. For example:
246
255
247
-
```pycon
256
+
```python
248
257
>>>print(f'{cost:0.2f}')
249
258
3220.00
250
259
>>>
251
260
```
252
261
253
-
Tuples are read-only. Verify this by trying to change the number of shares to 75.
262
+
Tuples are read-only. Verify this by trying to change the number of
263
+
shares to 75.
254
264
255
-
```pycon
265
+
```python
256
266
>>> t[1] =75
257
267
Traceback (most recent call last):
258
268
File "<stdin>", line 1, in<module>
259
269
TypeError: 'tuple'object does not support item assignment
260
270
>>>
261
271
```
262
272
263
-
Although you can’t change tuple contents, you can always create a completely new tuple that replaces the old one.
273
+
Although you can’t change tuple contents, you can always create a
274
+
completely new tuple that replaces the old one.
264
275
265
-
```pycon
276
+
```python
266
277
>>> t = (t[0], 75, t[2])
267
278
>>> t
268
279
('AA', 75, 32.2)
@@ -274,9 +285,10 @@ value is discarded. Although the above assignment might look like you
274
285
are modifying the tuple, you are actually creating a new tuple and
275
286
throwing the old one away.
276
287
277
-
Tuples are often used to pack and unpack values into variables. Try the following:
288
+
Tuples are often used to pack and unpack values into variables. Try
289
+
the following:
278
290
279
-
```pycon
291
+
```python
280
292
>>> name, shares, price = t
281
293
>>> name
282
294
'AA'
@@ -289,7 +301,7 @@ Tuples are often used to pack and unpack values into variables. Try the followin
289
301
290
302
Take the above variables and pack them back into a tuple
291
303
292
-
```pycon
304
+
```python
293
305
>>> t = (name, 2*shares, price)
294
306
>>> t
295
307
('AA', 150, 32.2)
@@ -300,7 +312,7 @@ Take the above variables and pack them back into a tuple
300
312
301
313
An alternative to a tuple is to create a dictionary instead.
302
314
303
-
```pycon
315
+
```python
304
316
>>> d = {
305
317
'name' : row[0],
306
318
'shares' : int(row[1]),
@@ -313,25 +325,27 @@ An alternative to a tuple is to create a dictionary instead.
313
325
314
326
Calculate the total cost of this holding:
315
327
316
-
```pycon
328
+
```python
317
329
>>> cost = d['shares'] * d['price']
318
330
>>> cost
319
331
3220.0000000000005
320
332
>>>
321
333
```
322
334
323
-
Compare this example with the same calculation involving tuples above. Change the number of shares to 75.
335
+
Compare this example with the same calculation involving tuples
336
+
above. Change the number of shares to 75.
324
337
325
-
```pycon
338
+
```python
326
339
>>> d['shares'] =75
327
340
>>> d
328
341
{'name': 'AA', 'shares': 75, 'price': 75}
329
342
>>>
330
343
```
331
344
332
-
Unlike tuples, dictionaries can be freely modified. Add some attributes:
345
+
Unlike tuples, dictionaries can be freely modified. Add some
346
+
attributes:
333
347
334
-
```pycon
348
+
```python
335
349
>>> d['date'] = (6, 11, 2007)
336
350
>>> d['account'] =12345
337
351
>>> d
@@ -343,15 +357,16 @@ Unlike tuples, dictionaries can be freely modified. Add some attributes:
343
357
344
358
If you turn a dictionary into a list, you’ll get all of its keys:
345
359
346
-
```pycon
360
+
```python
347
361
>>>list(d)
348
362
['name', 'shares', 'price', 'date', 'account']
349
363
>>>
350
364
```
351
365
352
-
Similarly, if you use the `for` statement to iterate on a dictionary, you will get the keys:
366
+
Similarly, if you use the `for` statement to iterate on a dictionary,
367
+
you will get the keys:
353
368
354
-
```pycon
369
+
```python
355
370
>>>for k in d:
356
371
print('k =', k)
357
372
@@ -365,7 +380,7 @@ k = account
365
380
366
381
Try this variant that performs a lookup at the same time:
367
382
368
-
```pycon
383
+
```python
369
384
>>>for k in d:
370
385
print(k, '=', d[k])
371
386
@@ -379,7 +394,7 @@ account = 12345
379
394
380
395
You can also obtain all of the keys using the `keys()` method:
0 commit comments