Created
January 20, 2016 12:00
-
-
Save amontalenti/56ca9c5357a24d796bbd to your computer and use it in GitHub Desktop.
Examples of using collections.namedtuple and collections.defaultdict, the "factory" collection types
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Example of using namedtuple: | |
>>> from collections import namedtuple | |
>>> Point = namedtuple("Point", "x y") | |
>>> point = Point(1, 2) | |
>>> point | |
Point(x=1, y=2) | |
>>> point.x | |
1 | |
>>> point.y | |
2 | |
>>> x, y = point | |
>>> x, y | |
(1, 2) | |
>>> point._asdict() | |
OrderedDict([('x', 1), ('y', 2)]) | |
>>> point == Point(**{'x': 1, 'y': 2}) | |
True | |
Example of using defaultdict: | |
>>> from collections import defaultdict | |
>>> counter = defaultdict(int) | |
>>> "x" in counter | |
False | |
>>> counter["x"] | |
0 | |
>>> counter["y"] += 1 | |
>>> counter["y"] | |
1 | |
>>> grouper = defaultdict(list) | |
>>> grouper["x"] | |
[] | |
>>> grouper["y"].append(1) | |
>>> grouper["y"] | |
[1] | |
""" | |
if __name__ == "__main__": | |
import doctest | |
doctest.testmod() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment