Python Collections Module

Last Updated : 26 Jul, 2025

The collections module in Python provides specialized containers (different from general purpose built-in containers like dict, list, tuple and set). These specialized containers are designed to address specific programming needs efficiently and offer additional functionalities.

Why do we need Collections Module?

  1. Provides specialized container data types beyond built-in types like list, dict and tuple.
  2. Includes efficient alternatives such as deque, Counter, OrderedDict, defaultdict and namedtuple.
  3. Simplifies complex data structure handling with cleaner and faster implementations.
  4. Helps in frequency counting, queue operations and structured records with minimal code.
  5. Ideal for improving performance and code readability in data-heavy applications.

Counters

A counter is a sub-class of the dictionary. It is used to keep the count of the elements in an iterable in the form of an unordered dictionary where the key represents element in the iterable and value represents the count of that element in the iterable.

Note: It is equivalent to bag or multiset of other languages.

Syntax:

class collections.Counter([iterable-or-mapping])

Initializing Counter Objects

The counter object can be initialized using counter() function and this function can be called in one of the following ways:

  • With a sequence of items
  • With a dictionary containing keys and counts
  • With keyword arguments mapping string names to counts

Example: Program to demonstrate different ways to create a Counter

Python
from collections import Counter 
  
# Creating Counter from a list (sequence of items)  
print(Counter(['B','B','A','B','C','A','B','B','A','C']))
  
# Creating Counter from a dictionary
print(Counter({'A':3, 'B':5, 'C':2}))
  
# Creating Counter using keyword arguments
print(Counter(A=3, B=5, C=2))

Output
Counter({'B': 5, 'A': 3, 'C': 2})
Counter({'B': 5, 'A': 3, 'C': 2})
Counter({'B': 5, 'A': 3, 'C': 2})

OrderedDict

An OrderedDict is a dictionary that preserves the order in which keys are inserted. While regular dictionaries do this from Python 3.7+, OrderedDict also offers extra features like moving re-inserted keys to the end making it useful for order-sensitive operations.

Syntax:

class collections.OrderDict()

Example:

Python
from collections import OrderedDict 
print("This is a Dict:\n") 
d = {} 
d['a'] = 1
d['b'] = 2
d['c'] = 3
d['d'] = 4
  
for key, value in d.items(): 
    print(key, value) 
  
print("\nThis is an Ordered Dict:\n") 
od = OrderedDict() 
od['a'] = 1
od['b'] = 2
od['c'] = 3
od['d'] = 4
  
for key, value in od.items(): 
    print(key, value) 

Output
This is a Dict:

a 1
b 2
c 3
d 4

This is an Ordered Dict:

a 1
b 2
c 3
d 4

While deleting and re-inserting the same key will push the key to the last to maintain the order of insertion of the key.

Example (Deleting and reinserting a key):

Python
from collections import OrderedDict 
od = OrderedDict() 
od['a'] = 1
od['b'] = 2
od['c'] = 3
od['d'] = 4
  
print('Before Deleting')
for key, value in od.items(): 
    print(key, value) 
    
# deleting element
od.pop('a')

# Re-inserting the same
od['a'] = 1

print('\nAfter re-inserting')
for key, value in od.items(): 
    print(key, value)

Output
Before Deleting
a 1
b 2
c 3
d 4

After re-inserting
b 2
c 3
d 4
a 1

DefaultDict

A DefaultDict is also a sub-class to dictionary. It is used to provide some default values for the key that does not exist and never raises a KeyError.

Syntax:

class collections.defaultdict(default_factory)

default_factory is a function that provides the default value for the dictionary created. If this parameter is absent then the KeyError is raised.

Initializing DefaultDict Objects

DefaultDict objects can be initialized using DefaultDict() method by passing the data type as an argument.

Example:

Python
from collections import defaultdict 

# Creating a defaultdict with default value of 0 (int)
d = defaultdict(int) 
L = [1, 2, 3, 4, 2, 4, 1, 2] 

# Counting occurrences of each element in the list
for i in L: 
    d[i] += 1  # No need to check key existence; default is 0

print(d)

Output
defaultdict(<class 'int'>, {1: 2, 2: 3, 3: 1, 4: 2})

Example 2:

Python
from collections import defaultdict 
  
# Defining a dict 
d = defaultdict(list) 
  
for i in range(5): 
    d[i].append(i) 
      
print("Dictionary with values as list:") 
print(d) 

Output
Dictionary with values as list:
defaultdict(<class 'list'>, {0: [0], 1: [1], 2: [2], 3: [3], 4: [4]})

ChainMap

A ChainMap encapsulates many dictionaries into a single unit and returns a list of dictionaries.

Syntax:

class collections.ChainMap(dict1, dict2)

Example:

Python
from collections import ChainMap 
   
d1 = {'a': 1, 'b': 2}
d2 = {'c': 3, 'd': 4}
d3 = {'e': 5, 'f': 6}

# Defining the chainmap 
c = ChainMap(d1, d2, d3) 
print(c)

Output
ChainMap({'a': 1, 'b': 2}, {'c': 3, 'd': 4}, {'e': 5, 'f': 6})

Accessing Keys and Values from ChainMap

Values from ChainMap can be accessed using the key name. They can also be accessed by using the keys() and values() method.

Example:

Python
from collections import ChainMap 
d1 = {'a': 1, 'b': 2}
d2 = {'c': 3, 'd': 4}
d3 = {'e': 5, 'f': 6}

# Defining the chainmap 
c = ChainMap(d1, d2, d3) 
   
# Accessing Values using key name
print(c['a'])

# Accessing values using values()
print(c.values())

# Accessing keys using keys()
print(c.keys())

Output
1
ValuesView(ChainMap({'a': 1, 'b': 2}, {'c': 3, 'd': 4}, {'e': 5, 'f': 6}))
KeysView(ChainMap({'a': 1, 'b': 2}, {'c': 3, 'd': 4}, {'e': 5, 'f': 6}))

Adding new dictionary

A new dictionary can be added by using the new_child() method. The newly added dictionary is added at the beginning of the ChainMap.

Example:

Python
import collections 
  
# initializing dictionaries 
dic1 = { 'a' : 1, 'b' : 2 } 
dic2 = { 'b' : 3, 'c' : 4 } 
dic3 = { 'f' : 5 } 
  
# initializing ChainMap 
chain = collections.ChainMap(dic1, dic2) 
  
# printing chainMap 
print ("All the ChainMap contents are: ") 
print (chain) 
  
# using new_child() to add new dictionary 
chain1 = chain.new_child(dic3