1
1
# Handy data types in the standard library
2
2
3
- [ ] (this doesn't explain how dict.setdefault and collections.defaultdict
4
- work because they're not as simple as the things that are here and i
3
+ [ ] (this doesn't explain how dict.setdefault and collections.defaultdict
4
+ work because they're not as simple as the things that are here and i
5
5
don't actually use them that much)
6
6
7
- Now we know how to ues lists, tuples and dictionaries. They are commonly
8
- used data types in Python, and there's nothing wrong with them. In this
9
- chapter we'll learn more data types that make some things easier. You
10
- can always do everything with lists and dictionaries, but these data
7
+ Now we know how to ues lists, tuples and dictionaries. They are commonly
8
+ used data types in Python, and there's nothing wrong with them. In this
9
+ chapter we'll learn more data types that make some things easier. You
10
+ can always do everything with lists and dictionaries, but these data
11
11
types can do a lot of the work for you.
12
12
13
13
> If it looks like a duck and quacks like a duck, it must be a duck.
14
14
15
- Many things in this tutorial are not really something but they behave
16
- like something. For example, we'll learn about many things that behave
17
- like dictionaries. They are not dictionaries, but we can use them just
18
- like if they were dictionaries. This programming style is known as
15
+ Many things in this tutorial are not really something but they behave
16
+ like something. For example, we'll learn about many things that behave
17
+ like dictionaries. They are not dictionaries, but we can use them just
18
+ like if they were dictionaries. This programming style is known as
19
19
** duck-typing** .
20
20
21
21
## Sets
22
22
23
- Let's say we have a program that keeps track of peoples' names. We can
24
- store the names in [ a list] ( ../basics/lists.md ) , and adding a new name
25
- is easy as appending to that list. Lists remember their order and it's
23
+ Let's say we have a program that keeps track of peoples' names. We can
24
+ store the names in [ a list] ( ../basics/lists.md ) , and adding a new name
25
+ is easy as appending to that list. Lists remember their order and it's
26
26
possible to add the same thing multiple times.
27
27
28
28
``` python
@@ -31,15 +31,15 @@ possible to add the same thing multiple times.
31
31
>> > names.append(' Akuli' )
32
32
>> > names
33
33
[' wub_wub' , ' theelous3' , ' RubyPinch' , ' go|dfish' , ' Nitori' , ' Akuli' , ' Akuli' ]
34
- >> >
34
+ >> >
35
35
```
36
36
37
- This is usually what we need, but sometimes it's not. Sometimes we just
38
- want to store a bunch of things. We don't need to have the same thing
37
+ This is usually what we need, but sometimes it's not. Sometimes we just
38
+ want to store a bunch of things. We don't need to have the same thing
39
39
twice and we don't care about the order.
40
40
41
- This is when sets come in. They are like lists without order or
42
- duplicates, or keys of [ dictionaries] ( ../basics/dicts.md ) without the
41
+ This is when sets come in. They are like lists without order or
42
+ duplicates, or keys of [ dictionaries] ( ../basics/dicts.md ) without the
43
43
values. We can create a set just like a dictionary, but without ` : ` .
44
44
45
45
``` python
53
53
>> >
54
54
```
55
55
56
- We can also convert anything [ iterable] ( ../basics/loops.md#summary ) to a
57
- set [ by calling the
58
- class] ( ../basics/classes.md#why-should-I-use-custom-classes-in-my-projects ) .
56
+ We can also convert anything [ iterable] ( ../basics/loops.md#summary ) to a
57
+ set [ by calling the
58
+ class] ( ../basics/classes.md#why-should-I-use-custom-classes-in-my-projects ) .
59
59
60
60
``` python
61
61
>> > set (' hello' )
62
62
{' o' , ' e' , ' h' , ' l' }
63
63
>> > type (set (' hello' ))
64
64
< class ' set' >
65
- >> >
65
+ >> >
66
66
```
67
67
68
- When we did ` set('hello') ` we lost one ` h ` and the set ended up in a
69
- different order because sets don't contain duplicates or keep track of
68
+ When we did ` set('hello') ` we lost one ` h ` and the set ended up in a
69
+ different order because sets don't contain duplicates or keep track of
70
70
their order.
71
71
72
- Note that ` {} ` is a dictionary because dictionaries are used more often
72
+ Note that ` {} ` is a dictionary because dictionaries are used more often
73
73
than sets, so we need ` set() ` if we want to create an empty set.
74
74
75
75
``` python
@@ -84,7 +84,7 @@ than sets, so we need `set()` if we want to create an empty set.
84
84
>> >
85
85
```
86
86
87
- Sets have a ` remove ` method just like lists have, but they have an ` add `
87
+ Sets have a ` remove ` method just like lists have, but they have an ` add `
88
88
method instead of ` append ` .
89
89
90
90
``` python
@@ -98,24 +98,24 @@ method instead of `append`.
98
98
>> >
99
99
```
100
100
101
- That's the boring part. Now let's have a look at some really handy
101
+ That's the boring part. Now let's have a look at some really handy
102
102
things we can do with sets:
103
103
104
104
``` python
105
105
>> > a = {' RubyPinch' , ' theelous3' , ' go|dfish' }
106
106
>> > b = {' theelous3' , ' Nitori' }
107
107
>> > a & b # names in a and b
108
108
{' theelous3' }
109
- >> > a | b # names in a, b or both
109
+ >> > a | b # names in a, b or both
110
110
{' Nitori' , ' theelous3' , ' go|dfish' , ' RubyPinch' }
111
111
>> > a ^ b # names in a or b, but not both
112
112
{' RubyPinch' , ' Nitori' , ' go|dfish' }
113
- >> >
113
+ >> >
114
114
```
115
115
116
116
## Named tuples
117
117
118
- It can be tempting to make a class that just contains a bunch of data
118
+ It can be tempting to make a class that just contains a bunch of data
119
119
and that's it.
120
120
121
121
``` python
@@ -130,16 +130,16 @@ class Website:
130
130
github = Website(' https://github.com/' , 2008 , True )
131
131
```
132
132
133
- You should avoid making classes like this. This class has only one
134
- method, so it doesn't really need to be a class. We could just use a
133
+ You should avoid making classes like this. This class has only one
134
+ method, so it doesn't really need to be a class. We could just use a
135
135
tuple instead:
136
136
137
137
``` python
138
138
github = (' https://github.com/' , 2008 , True )
139
139
```
140
140
141
- The problem with this is that if someone reading our code sees something
142
- like ` website[1] > 2010 ` it doesn't make much sense, like
141
+ The problem with this is that if someone reading our code sees something
142
+ like ` website[1] > 2010 ` it doesn't make much sense, like
143
143
` website.founding_year > 2010 ` would.
144
144
145
145
In cases like this, ` collections.namedtuple ` is handy:
@@ -151,7 +151,7 @@ In cases like this, `collections.namedtuple` is handy:
151
151
2008
152
152
>> > for thing in github:
153
153
... print (thing)
154
- ...
154
+ ...
155
155
https:// github.com/
156
156
2008
157
157
True
@@ -162,13 +162,13 @@ Website(url='https://github.com/', founding_year=2008, free_to_use=True)
162
162
>> >
163
163
```
164
164
165
- As you can see, our ` github ` behaves like a tuple, but things like
166
- ` github.founding_year ` also work and ` github ` looks nice when we have a
165
+ As you can see, our ` github ` behaves like a tuple, but things like
166
+ ` github.founding_year ` also work and ` github ` looks nice when we have a
167
167
look at it on the ` >>> ` prompt.
168
168
169
169
## Deques
170
170
171
- To understand deques, we need to first learn about a list method I
171
+ To understand deques, we need to first learn about a list method I
172
172
haven't talked about earlier. It's called ` pop ` and it works like this:
173
173
174
174
``` python
@@ -186,14 +186,14 @@ haven't talked about earlier. It's called `pop` and it works like this:
186
186
>> >
187
187
```
188
188
189
- The list shortens from the end by one when we pop from it, and we also
190
- get the removed item back. So we can add an item to the end of a list
189
+ The list shortens from the end by one when we pop from it, and we also
190
+ get the removed item back. So we can add an item to the end of a list
191
191
using ` append ` , and we can remove an item from the end using ` pop ` .
192
192
193
- It's also possible to do these things in the beginning of a list, but
194
- lists were not designed to be used that way and it would be slow if our
195
- list would be big. The ` collections.deque ` class makes appending and
196
- popping from both ends easy and fast. It works just like lists, but it
193
+ It's also possible to do these things in the beginning of a list, but
194
+ lists were not designed to be used that way and it would be slow if our
195
+ list would be big. The ` collections.deque ` class makes appending and
196
+ popping from both ends easy and fast. It works just like lists, but it
197
197
also has ` appendleft ` and ` popleft ` methods.
198
198
199
199
``` python
@@ -210,18 +210,18 @@ deque(['wub_wub', 'theelous3', 'Nitori', 'RubyPinch', 'go|dfish'])
210
210
' go|dfish'
211
211
>> > names
212
212
deque([' theelous3' , ' Nitori' , ' RubyPinch' ])
213
- >> >
213
+ >> >
214
214
```
215
215
216
- The deque behaves a lot like lists do, and we can do ` list(names) ` if we
216
+ The deque behaves a lot like lists do, and we can do ` list(names) ` if we
217
217
need a list instead of a deque for some reason.
218
218
219
- Deques are often used as queues. It means that items are always added to
219
+ Deques are often used as queues. It means that items are always added to
220
220
one end and popped from the other end.
221
221
222
222
## Counting things
223
223
224
- Back in [ the dictionary chapter] ( ../basics/dicts.md#examples ) we learned
224
+ Back in [ the dictionary chapter] ( ../basics/dicts.md#examples ) we learned
225
225
to count the number of words in a sentence like this:
226
226
227
227
``` python
@@ -234,9 +234,9 @@ for word in sentence.split():
234
234
counts[word] = 1
235
235
```
236
236
237
- This code works just fine, but there are easier ways to do this. For
238
- example, we could use the ` get ` method. It works so that
239
- ` the_dict.get('hi', 'hello') ` tries to give us ` the_dict['hi'] ` but
237
+ This code works just fine, but there are easier ways to do this. For
238
+ example, we could use the ` get ` method. It works so that
239
+ ` the_dict.get('hi', 'hello') ` tries to give us ` the_dict['hi'] ` but
240
240
gives us ` 'hello' ` instead if ` 'hi' ` is not in the dictionary.
241
241
242
242
``` python
@@ -257,8 +257,8 @@ for word in sentence.split():
257
257
counts[word] = counts.get(word, 0 ) + 1
258
258
```
259
259
260
- Counting things like this is actually so common that there's [ a
261
- class] ( ../basics/classes.md ) just for that. It's called
260
+ Counting things like this is actually so common that there's [ a
261
+ class] ( ../basics/classes.md ) just for that. It's called
262
262
` collections.Counter ` and it works like this:
263
263
264
264
``` python
@@ -267,25 +267,25 @@ class](../basics/classes.md) just for that. It's called
267
267
>> > counts = collections.Counter(words)
268
268
>> > counts
269
269
Counter({' test' : 2 , ' hello' : 2 , ' is' : 1 , ' this' : 1 , ' there' : 1 , ' a' : 1 })
270
- >> >
270
+ >> >
271
271
```
272
272
273
- Now ` counts ` is a Counter object. It behaves a lot like a dictionary,
274
- and everything that works with a dictionary should also work with a
275
- counter. We can also convert the counter to a dictionary by doing
273
+ Now ` counts ` is a Counter object. It behaves a lot like a dictionary,
274
+ and everything that works with a dictionary should also work with a
275
+ counter. We can also convert the counter to a dictionary by doing
276
276
` dict(the_counter) ` if something doesn't work with a counter.
277
277
278
278
``` python
279
279
>> > for word, count in counts.items():
280
280
... print (word, count)
281
- ...
281
+ ...
282
282
test 2
283
283
is 1
284
284
this 1
285
285
there 1
286
286
a 1
287
287
hello 2
288
- >> >
288
+ >> >
289
289
```
290
290
291
291
## Combining dictionaries
@@ -301,7 +301,7 @@ We can add together strings, lists, tuples and sets easily.
301
301
(1 , 2 , 3 , 4 , 5 )
302
302
>> > {1 , 2 , 3 } | {4 , 5 }
303
303
{1 , 2 , 3 , 4 , 5 }
304
- >> >
304
+ >> >
305
305
```
306
306
307
307
But how about dictionaries? They can't be added together with ` + ` .
@@ -311,10 +311,10 @@ But how about dictionaries? They can't be added together with `+`.
311
311
Traceback (most recent call last):
312
312
File " <stdin>" , line 1 , in < module>
313
313
TypeError : unsupported operand type (s) for + : ' dict' and ' dict'
314
- >> >
314
+ >> >
315
315
```
316
316
317
- Dictionaries have an `update` method that adds everything from another
317
+ Dictionaries have an `update` method that adds everything from another
318
318
dictionary into it. So we can merge dictionaries like this:
319
319
320
320
```python
@@ -323,7 +323,7 @@ dictionary into it. So we can merge dictionaries like this:
323
323
>> > merged.update({' c' : 3 })
324
324
>> > merged
325
325
{' c' : 3 , ' b' : 2 , ' a' : 1 }
326
- >> >
326
+ >> >
327
327
```
328
328
329
329
Or we can [write a function](../ basics/ defining- functions.md) like this:
@@ -340,8 +340,8 @@ Or we can [write a function](../basics/defining-functions.md) like this:
340
340
>> >
341
341
```
342
342
343
- Kind of like counting things, merging dictionaries is also a commonly
344
- needed thing and there' s a class just for it in the `collections`
343
+ Kind of like counting things, merging dictionaries is also a commonly
344
+ needed thing and there' s a class just for it in the `collections`
345
345
module. It' s called ChainMap:
346
346
347
347
```python
@@ -352,36 +352,47 @@ ChainMap({'b': 2, 'a': 1}, {'c': 3})
352
352
>> >
353
353
```
354
354
355
- Our `merged` is kind of like the Counter object we created earlier. It' s
355
+ Our `merged` is kind of like the Counter object we created earlier. It' s
356
356
not a dictionary, but it behaves like a dictionary.
357
357
358
358
```python
359
359
>> > for key, value in merged.items():
360
360
... print (key, value)
361
- ...
361
+ ...
362
362
c 3
363
363
b 2
364
364
a 1
365
365
>> > dict (merged)
366
366
{' c' : 3 , ' b' : 2 , ' a' : 1 }
367
- >> >
367
+ >> >
368
368
```
369
369
370
- Starting with Python 3.5 it' s possible to merge dictionaries like this.
371
- ** Don' t do this unless you are sure that no-one will need to run your
370
+ Starting with Python 3.5 it' s possible to merge dictionaries like this.
371
+ ** Don' t do this unless you are sure that no-one will need to run your
372
372
code on Python versions older than 3.5 .**
373
373
374
374
```python
375
375
>> > first = {' a' : 1 , ' b' : 2 }
376
376
>> > second = {' c' : 3 , ' d' : 4 }
377
377
>> > {** first, ** second}
378
378
{' d' : 4 , ' c' : 3 , ' a' : 1 , ' b' : 2 }
379
- >> >
379
+ >> >
380
380
```
381
381
382
382
# # Summary
383
383
384
- - Duck typing means requiring some behavior instead of some type . For
385
- example, instead of making a function that takes a list we could make
384
+ - Duck typing means requiring some behavior instead of some type . For
385
+ example, instead of making a function that takes a list we could make
386
386
a function that takes anything [iterable](../ basics/ loops.md# summary).
387
387
- Sets and the collections module are handy. Use them.
388
+
389
+ ** *
390
+
391
+ If you like this tutorial, please [give it a
392
+ star](../ README .md# how-can-i-thank-you-for-writing-and-sharing-this-tutorial).
393
+
394
+ You may use this tutorial freely at your own risk. See
395
+ [LICENSE ](../ LICENSE ).
396
+
397
+ [Previous](../ basics/ classes.md) | [Next](functions.md) |
398
+ [List of contents](../ README .md# advanced)
0 commit comments