Collections module


In [1]:
from collections import *

1 Counter

A Counter is a dict subclass for counting hashable objects. It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values.

1.1 construction


In [4]:
c1 = Counter()
c2 = Counter('gaufung')
c3 = Counter({'red':4,'blue':10})
c4 = Counter(cats=4,dogs=5)

1.2 using key


In [8]:
c = Counter(['dog', 'cat'])
c['fox']


Out[8]:
0

1.3 delete key

Setting a count to zero does not remove an element from a counter. Use del to remove it entirely:


In [13]:
c['dog'] = 0
del c['dog']

1.4 elements

Return an iterator over elements repeating each as many times as its count.


In [14]:
c = Counter(a=4, b=2, c=0, d=-2)
print list(c.elements())


['a', 'a', 'a', 'a', 'b', 'b']

1.5 most_common

Return a list of the n most common elements and their counts from the most common to the least.


In [16]:
Counter('abracadabra').most_common(3)


Out[16]:
[('a', 5), ('r', 2), ('b', 2)]

1.6 subtract([iterable-or-mapping])

Elements are subtracted from an iterable or from another mapping (or counter).


In [17]:
c = Counter(a=4, b=2, c=0, d=-2)
d = Counter(a=1, b=2, c=3, d=4)
c.subtract(d)
c


Out[17]:
Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6})

2 deque

Deques are a generalization of stacks and queues,Deques support thread-safe, memory efficient appends and pops from either side of the deque with approximately the same O(1) performance in either direction.

  • append(x)
    Add x to the right side of the deque.

  • appendleft(x)
    Add x to the left side of the deque.

  • clear()
    Remove all elements from the deque leaving it with length 0.

  • count(x)
    Count the number of deque elements equal to x.

  • extend(iterable)
    Extend the right side of the deque by appending elements from the iterable argument.

  • extendleft(iterable)
    Extend the left side of the deque by appending elements from iterable. Note, the series of left appends results in reversing the order of elements in the iterable argument.

  • pop()
    Remove and return an element from the right side of the deque. If no elements are present, raises an IndexError.

  • popleft()
    Remove and return an element from the left side of the deque. If no elements are present, raises an IndexError.

  • remove(value)
    Removed the first occurrence of value. If not found, raises a ValueError.

  • reverse()
    Reverse the elements of the deque in-place and then return None.

  • rotate(n)
    Rotate the deque n steps to the right. If n is negative, rotate to the left. Rotating one step to the right is equivalent to: d.appendleft(d.pop()).

  • maxlen
    Maximum size of a deque or None if unbounded.

3 defaultdict

dictionary supply missing values


In [18]:
s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
d = defaultdict(list)
for k, v in s:
    d[k].append(v)
d.items()


Out[18]:
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]

4 namedtuple

Named tuples assign meaning to each position in a tuple and allow for more readable, self-documenting code. They can be used wherever regular tuples are used, and they add the ability to access fields by name instead of position index.

namedtuple(typename, field_names[, verbose=False][, rename=False])


In [19]:
Point = namedtuple('Point', ['x', 'y'], verbose=True)


class Point(tuple):
    'Point(x, y)'

    __slots__ = ()

    _fields = ('x', 'y')

    def __new__(_cls, x, y):
        'Create new instance of Point(x, y)'
        return _tuple.__new__(_cls, (x, y))

    @classmethod
    def _make(cls, iterable, new=tuple.__new__, len=len):
        'Make a new Point object from a sequence or iterable'
        result = new(cls, iterable)
        if len(result) != 2:
            raise TypeError('Expected 2 arguments, got %d' % len(result))
        return result

    def __repr__(self):
        'Return a nicely formatted representation string'
        return 'Point(x=%r, y=%r)' % self

    def _asdict(self):
        'Return a new OrderedDict which maps field names to their values'
        return OrderedDict(zip(self._fields, self))

    def _replace(_self, **kwds):
        'Return a new Point object replacing specified fields with new values'
        result = _self._make(map(kwds.pop, ('x', 'y'), _self))
        if kwds:
            raise ValueError('Got unexpected field names: %r' % kwds.keys())
        return result

    def __getnewargs__(self):
        'Return self as a plain tuple.  Used by copy and pickle.'
        return tuple(self)

    __dict__ = _property(_asdict)

    def __getstate__(self):
        'Exclude the OrderedDict from pickling'
        pass

    x = _property(_itemgetter(0), doc='Alias for field number 0')

    y = _property(_itemgetter(1), doc='Alias for field number 1')



In [20]:
p = Point(11, y=22)
p


Out[20]:
Point(x=11, y=22)

5 Orderdict

Ordered dictionaries are just like regular dictionaries but they remember the order that items were inserted.