EZ

Eduzan

Learning Hub

Eduzan
Eduzan / Python

Python Collections Module

Computer Science / Python tutorial chapter - Published 2025-12-17 - Python

The Python collections module provides a variety of specialized container types to optimize different storage and retrieval operations. Here’s a breakdown of the key classes:

1. Counter

Counter is a dictionary subclass for counting hashable objects. It stores elements as dictionary keys and their counts as dictionary values. You can initialize a Counter with an iterable, a dictionary, or keyword arguments.

Example:

from collections import Counter

# With sequence of items
print(Counter(['B','B','A','B','C','A','B','B','A','C']))
# Output: Counter({'B': 5, 'A': 3, 'C': 2})

# with dictionary
print(Counter({'A': 3, 'B': 5, 'C': 2}))
# Output: Counter({'B': 5, 'A': 3, 'C': 2})

# with keyword arguments
print(Counter(A=3, B=5, C=2))
# Output: Counter({'B': 5, 'A': 3, 'C': 2})

2. OrderedDict

OrderedDict is a dictionary subclass that maintains the order of items as they are inserted. Deleting and reinserting a key moves it to the end.

Example:

from collections import OrderedDict

# Regular dictionary
d = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
print("This is a Dict:")
for key, value in d.items():
    print(key, value)
# Output:
# a 1
# b 2
# c 3
# d 4

# Ordered dictionary
od = OrderedDict(d)
print("\nThis is an Ordered Dict:")
for key, value in od.items():
    print(key, value)
# Output:
# a 1
# b 2
# c 3
# d 4

3. DefaultDict

DefaultDict provides default values for missing keys to avoid KeyError. It’s initialized with a default factory function.

Example:

from collections import defaultdict

# DefaultDict with int
d = defaultdict(int)
L = [1, 2, 3, 4, 2, 4, 1, 2]
for i in L:
    d[i] += 1
print(d)
# Output: defaultdict(<class 'int'>, {1: 2, 2: 3, 3: 1, 4: 2})

# DefaultDict with list
d = defaultdict(list)
for i in range(5):
    d[i].append(i)
print(d)
# Output: defaultdict(<class 'list'>, {0: [0], 1: [1], 2: [2], 3: [3], 4: [4]})

4. ChainMap

ChainMap combines multiple dictionaries into one. This is useful for managing multiple contexts in a single view.

Example:

from collections import ChainMap

d1 = {'a': 1, 'b': 2}
d2 = {'c': 3, 'd': 4}
d3 = {'e': 5, 'f': 6}
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
print(c['a'])
# Output: 1
print(c.values())
# Output: ValuesView(ChainMap({'a': 1, 'b': 2}, {'c': 3, 'd': 4}, {'e': 5, 'f': 6}))
print(c.keys())
# Output: KeysView(ChainMap({'a': 1, 'b': 2}, {'c': 3, 'd': 4}, {'e': 5, 'f': 6}))

# Adding new dictionary
chain = c.new_child({'f': 7})
print(chain)
# Output: ChainMap({'f': 7}, {'a': 1, 'b': 2}, {'c': 3, 'd': 4}, {'e': 5, 'f': 6})

5. NamedTuple

NamedTuple extends tuple with named fields, making code clearer.

Example:

from collections import namedtuple

Student = namedtuple('Student', ['name', 'age', 'DOB'])
S = Student('Nandini', '19', '2541997')
print(S[1])  # Output: 19
print(S.name)  # Output: Nandini

# _make() and _asdict()
li = ['Manjeet', '19', '411997']
print(Student._make(li))
# Output: Student(name='Manjeet', age='19', DOB='411997')
print(S._asdict())
# Output: OrderedDict([('name', 'Nandini'), ('age', '19'), ('DOB', '2541997')])

6. Deque

Deque (double-ended queue) allows fast appends and pops from both ends.

Example:

from collections import deque

# Declaring deque
queue = deque(['name', 'age', 'DOB'])
print(queue)
# Output: deque(['name', 'age', 'DOB'])

# Append and appendleft
de = deque([1, 2, 3])
de.append(4)
print(de)
# Output: deque([1, 2, 3, 4])
de.appendleft(6)
print(de)
# Output: deque([6, 1, 2, 3, 4])

# Pop and popleft
de.pop()
print(de)
# Output: deque([6, 1, 2, 3])
de.popleft()
print(de)
# Output: deque([1, 2, 3])

7. UserDict, UserList, UserString

These classes allow users to subclass and create modified dictionary, list, or string behaviors by acting as wrappers around built-in types.

UserDict Example:

from collections import UserDict

class MyDict(UserDict):
    def __del__(self):
        raise RuntimeError("Deletion not allowed")
    def pop(self, s=None):
        raise RuntimeError("Deletion not allowed")
    def popitem(self, s=None):
        raise RuntimeError("Deletion not allowed")

d = MyDict({'a': 1, 'b': 2, 'c': 3})
d.pop(1)
# Output: RuntimeError: Deletion not allowed

UserList

from collections import UserList

class MyList(UserList):
    def remove(self, s=None):
        raise RuntimeError("Deletion not allowed")
    def pop(self, s=None):
        raise RuntimeError("Deletion not allowed")

L = MyList([1, 2, 3, 4])
L.append(5)
print(L)
# Output: [1, 2, 3, 4, 5]
L.remove()
# Output: RuntimeError: Deletion not allowed

UserString

from collections import UserString

class MyString(UserString):
    def append(self, s):
        self.data += s
    def remove(self, s):
        self.data = self.data.replace(s, "")

s1 = MyString("Hello")
s1.append(" World")
print(s1)
# Output: Hello World
s1.remove("l")
print(s1)
# Output: Heo Word
End of lesson.