Ticker

6/recent/ticker-posts

Collections Module in Python

Collections Module in Python

Introduction
The collections module in Python provides specialized container data types that are more efficient and convenient than the built-in data types. It includes several classes to handle collections, such as namedtuples, defaultdict, OrderedDict, Counter, and deque.

1. Namedtuples
Namedtuples are tuples with named fields, making the code more readable and self-documenting. They are immutable and support all tuple operations. Here's an example:

python
from collections import namedtuple

# Define a named tuple 'Point' with fields 'x' and 'y'
Point = namedtuple('Point', ['x', 'y'])

# Create an instance of 'Point'
p1 = Point(1, 2)

# Access fields by name
print(p1.x) # Output: 1
print(p1.y) # Output: 2

2. defaultdict
The defaultdict is a subclass of the built-in dictionary that provides a default value for non-existing keys. This is useful when counting occurrences or creating nested data structures.

python
from collections import defaultdict

# Create a defaultdict with the default value of 0
fruit_counts = defaultdict(int)

# Increment the count of each fruit
fruits = ['apple', 'banana', 'apple', 'orange', 'banana']
for fruit in fruits:
fruit_counts[fruit] += 1

print(fruit_counts)
# Output: defaultdict(<class 'int'>, {'apple': 2, 'banana': 2, 'orange': 1})

3. OrderedDict
An OrderedDict is a dictionary subclass that remembers the order of key insertion. This ensures that the order of items remains consistent, which is useful in some scenarios.

python
from collections import OrderedDict

# Create an OrderedDict
ordered_dict = OrderedDict()

# Insert key-value pairs in a specific order
ordered_dict['one'] = 1
ordered_dict['two'] = 2
ordered_dict['three'] = 3

print(ordered_dict)
# Output: OrderedDict([('one', 1), ('two', 2), ('three', 3)])

4. Counter
The Counter class is used for counting hashable objects. It returns a dictionary with elements as keys and their counts as values.

python
from collections import Counter

# Create a Counter for a list of items
items = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
item_counts = Counter(items)

print(item_counts)
# Output: Counter({'apple': 3, 'banana': 2, 'orange': 1})

# Access the count of a specific item
print(item_counts['apple']) # Output: 3

5. deque
A deque (double-ended queue) is a data structure that allows efficient insertion and deletion from both ends. It is useful for implementing queues and stacks efficiently.

python
from collections import deque

# Create a deque
d = deque()

# Add elements to the right side
d.append(1)
d.append(2)

# Add elements to the left side
d.appendleft(3)
d.appendleft(4)

print(d)
# Output: deque([4, 3, 1, 2])

These are some of the essential classes provided by the collections module in Python. They offer powerful data structures to make your code more concise and efficient.

Post a Comment

0 Comments