Jan 19, 2012

Python Standard Library: Collections

Counter

Dict subclass for counting hashable items. Sometimes called a bag or multiset. Elements are stored as dictionary keys and their counts are stored as dictionary values.
Counter(['a', 'b', 'c', 'a'])
# Counter({'a': 2, 'c': 1, 'b': 1})

namedtuple

Returns a new subclass of tuple with named fields.
Point = namedtuple('Point', 'x y z')
Point.__doc__
# 'Point(x, y, z)'
p = Point(x=1, y=2, z=3)
print p.x, p.y, p.z
# 1 2 3

No comments: