The collections module in Python provides specialized container datatypes that are alternatives to the general-purpose built-in containers like "lists", "tuples", "dictionaries", and "sets".
These specialized containers offer additional functionalities and optimizations for common use cases.
Common data types provided by the collections module:
It creates tuple-like objects that have fields accessible by attribute lookup as well as by index.
# import namedtuple from collections module from collections import namedtuple # Creating Point Class using namedtuple class and defines its attributes as well Point = namedtuple('Point', ['x', 'y']) p = Point(1, 2) # Checking Type of Point object print(type(p)) # Output: <class '__main__.Point'> print(p.x, p.y) # Output: 1 2
It is a double-ended queue that supports adding and removing elements from both ends efficiently.
# import deque class from collections module from collections import deque # Creating deque object d = deque([1, 2, 3])
print(d.append(4)) # Output: None # print updated list print(d) # Output: [1, 2, 3, 4]
print(d.appendleft(0)) # Output: None # print updated list print(d) # Output: [0, 1, 2, 3, 4]
print(d.pop()) # Output: 4 # print updated list print(d) # Output: [0, 1, 2, 3]
print(d.popleft()) # Output: 0 # print updated list print(d) # Output: [1, 2, 3]
It is a dictionary subclass that counts hashable objects and is used to count occurrences of elements in a list or any other iterable.
from collections import Counter c = Counter(['a', 'b', 'a', 'c', 'b', 'a', 'd', 'e']) print(c) # Output: Counter({'a': 3, 'b': 2, 'c': 1, 'd': 1, 'e': 1})
It is a dictionary subclass that calls a factory function to supply missing values.
from collections import defaultdict d = defaultdict(int) d['a'] += 1 print(d['a']) # Output: 1
It is a dictionary subclass that remembers the order in which its contents are added and uses its methods such as keys() and values() to retrieve keys and values from the OrderedDict instance.
from collections import OrderedDict # create OrderedDict object using OrderedDict Class orderedDict = OrderedDict() # Checking Type of orderedDict object print(type(orderedDict)) # Output: <class 'collections.OrderedDict'>
orderedDict['age'] = 24 orderedDict['orgId'] = 3001 orderedDict['name'] = "Alice"
print(orderedDict.keys()) # Output: odict_keys(['age', 'orgId', 'name'])
print(orderedDict.values()) # Output: odict_values([24, 3001, 'Alice'])
It is a dictionary-like class for creating a single view of multiple mappings.
from collections import ChainMap dict1 = {'firstName': "Alice", 'lastName': "Collin"} dict2 = {'orgId': 101, 'orgName': "XYZ"} # create ChainMap using dictionary object chainMap = ChainMap(dict1, dict2) # Print the result from chainMap print(chainMap['firstName']) # Output: Alice # Checking Type of chainMap print(type(chainMap)) # Output: <class 'collections.ChainMap'> # Print the result from chainMap print(chainMap['orgId']) # Output: 101 # Checking object of chainMap is ChainMap print(isinstance(chainMap, ChainMap)) # Output: True
These are just a few examples of what we can do with the collections module.
It provides various other useful data types and functions for specialized use cases.
Always ensure to import the specific data type or function we need from the collections module (from collections import ...) before using it.