Python From Beginner to Advanced

0% completed

Previous
Next
Python - Collections Module

The Python Collections module enhances the functionality of the built-in collection types like dictionaries, lists, sets, and tuples with specialized container datatypes. This module offers alternatives to Python’s general-purpose built-in containers and is designed to provide additional tools and methods which allow Python programmers to handle data more efficiently and with simpler code.

In this lesson, we will explore some of the most useful collections provided by this module, illustrating each with practical examples.

Image

Counters

A Counter is a subclass of the dictionary object which is designed to count hashable objects. It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values.

Example

In this example, we will count the occurrences of each character in a string.

Python3
Python3

. . . .

Explanation:

  • from collections import Counter imports the Counter class from the collections module.
  • character_count = Counter(example_string) creates a Counter object and counts each character in the string "hello".
  • print(character_count) outputs Counter({'l': 2, 'h': 1, 'e': 1, 'o': 1}), showing each character's count in the string.

OrderedDict

An OrderedDict is a dictionary subclass that remembers the order in which its contents are added.

Example

In this example, we will show how the OrderedDict preserves the order of insertion.

Python3
Python3

. . . .

Explanation:

  • from collections import OrderedDict imports the OrderedDict class.
  • ordered_dict = OrderedDict() initializes an empty OrderedDict.
  • Next, Items are added in the order 'a', 'b', 'c' with values 'A', 'B', 'C'.
  • print(ordered_dict) will display OrderedDict([('a', 'A'), ('b', 'B'), ('c', 'C')]), maintaining the order they were added.

DefaultDict

A defaultdict is similar to the usual dictionary container, but it provides a default value for the key that does not exist.

Example

In this example, we will use a defaultdict to handle keys not found in the dictionary.

Python3
Python3

. . . .

Explanation:

  • from collections import defaultdict imports the defaultdict class.
  • default_dict = defaultdict(int) initializes a defaultdict with a default factory function int, which returns 0.
  • Next, we set values for keys 'a' and 'b'.
  • print(default_dict['c']) shows 0, demonstrating the default value assigned to non-existent keys.

ChainMap

A ChainMap groups multiple dictionaries into a single view.

Example

In this example, we will combine two dictionaries using ChainMap.

Python3
Python3

. . . .

Explanation:

  • from collections import ChainMap imports the ChainMap class.
  • combined_dict = ChainMap(dict1, dict2) creates a single view that shows the contents of dict1 and dict2 as if they were a single dictionary.
  • print(combined_dict) outputs the contents showing dict1 taking precedence where keys overlap.

NamedTuple

The namedtuple() factory function creates tuple subclasses with named fields.

Example

In this example, we will create a namedtuple representing a point in 2D space.

Python3
Python3

. . . .

Explanation:

  • from collections import namedtuple imports the namedtuple function.
  • Point = namedtuple('Point', ['x', 'y']) defines a Point as a namedtuple with 'x' and 'y' as fields.
  • point = Point(10, 20) creates an instance of Point.
  • print(point.x, point.y) displays the values 10 and 20, showing how fields in namedtuple can be accessed.

Deque

A deque, or double-ended queue, is an optimized list-like sequence that allows fast appends and pops from both ends. It is ideal for queues and breadth-first tree searches where you need to add and remove items quickly from both the front and the back.

Example

In this example, we demonstrate basic operations like appending and popping elements using a deque.

Python3
Python3

. . . .

Explanation:

  • from collections import deque imports the deque class from the collections module.
  • d = deque() creates an empty deque.
  • d.append('a') and d.appendleft('b') demonstrate adding elements to the right and left ends of the deque, respectively.
  • print('After append:', list(d)) shows the deque state after the additions.
  • d.pop() and d.popleft() demonstrate removing elements from the right and left ends, respectively.
  • print('After pop:', list(d)) displays the deque after items have been removed, confirming the changes.

These enhanced data structures are particularly useful when you need to add custom behavior or constraints to the basic collections provided by Python.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next