Python Collections Module
The collections module implements specialized container datatypes providing alternatives to Pythonβs general purpose built-in containers, dict, list, set, and tuple.
Importing the Module
import collections
Counter
A Counter is a dict subclass for counting hashable objects.
from collections import Counter
cnt = Counter(['red', 'blue', 'red', 'green', 'blue', 'blue'])
print(cnt)
# Output: Counter({'blue': 3, 'red': 2, 'green': 1})
# Most common elements
print(cnt.most_common(2))
defaultdict
A defaultdict works exactly like a dictionary, but it is initialized with a function ("default factory") that takes no arguments and provides the default value for a nonexistent key.
from collections import defaultdict
# Default value is an empty list
d = defaultdict(list)
d['python'].append('awesome')
d['java'].append('verbose')
print(d['python']) # ['awesome']
print(d['c++']) # [] (No KeyError, returns default)
namedtuple
Factory function for creating tuple subclasses with named fields.
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(11, y=22)
print(p.x, p.y) # Access by name
print(p[0], p[1]) # Access by index
deque
A deque (double-ended queue) is a list-like container with fast appends and pops on either end.
from collections import deque
d = deque(['a', 'b', 'c'])
d.append('d') # Add to right
d.appendleft('z') # Add to left
d.pop() # Remove from right
d.popleft() # Remove from left
OrderedDict
A dictionary subclass that remembers the order in which entries were added.
Note: As of Python 3.7, standard dicts also preserve insertion order, but OrderedDict has some extra methods like move_to_end.
from collections import OrderedDict
od = OrderedDict()
od['a'] = 1
od['b'] = 2
od.move_to_end('a')
print(list(od.keys())) # ['b', 'a']