Skip to content

Instantly share code, notes, and snippets.

@amontalenti
Created January 20, 2016 12:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amontalenti/56ca9c5357a24d796bbd to your computer and use it in GitHub Desktop.
Save amontalenti/56ca9c5357a24d796bbd to your computer and use it in GitHub Desktop.
Examples of using collections.namedtuple and collections.defaultdict, the "factory" collection types
"""
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