0% completed
Python - Collections Module
On This Page
Counters
Example
OrderedDict
Example
DefaultDict
Example
ChainMap
Example
NamedTuple
Example
Deque
Example
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.
Counters
A Counter is a subclass of the dictionary object which is designed to count hashable objects. It is a 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.
Explanation:
from collections import Counterimports theCounterclass from the collections module.character_count = Counter(example_string)creates aCounterobject and counts each character in the string"hello".print(character_count)outputsCounter({'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.
Explanation:
from collections import OrderedDictimports theOrderedDictclass.ordered_dict = OrderedDict()initializes an emptyOrderedDict.- Next, items are added in the order 'a', 'b', 'c' with values 'A', 'B', 'C'.
print(ordered_dict)will displayOrderedDict({'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.
Explanation:
from collections import defaultdictimports thedefaultdictclass.default_dict = defaultdict(int)initializes adefaultdictwith a default factory functionint, which returns0.- Next, we set values for keys 'a' and 'b'.
print(default_dict['c'])shows0, 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.
Explanation:
from collections import ChainMapimports theChainMapclass.combined_dict = ChainMap(dict1, dict2)creates a single view that shows the contents ofdict1anddict2as if they were a single dictionary.print(combined_dict)printsChainMap({'a': 1, 'b': 2}, {'b': 3, 'c': 4}), the dictionaries it holds in search order. Precedence shows when you look up a key:combined_dict['b']returns2, becausedict1is searched first.
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.
Explanation:
from collections import namedtupleimports thenamedtuplefunction.Point = namedtuple('Point', ['x', 'y'])defines aPointas anamedtuplewith 'x' and 'y' as fields.point = Point(10, 20)creates an instance ofPoint.print(point.x, point.y)displays the values10and20, showing how fields innamedtuplecan 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.
Explanation:
from collections import dequeimports thedequeclass from the collections module.d = deque()creates an empty deque.d.append('a')andd.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()andd.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.
Reading Progress
0%
On This Page
Counters
Example
OrderedDict
Example
DefaultDict
Example
ChainMap
Example
NamedTuple
Example
Deque
Example