Exploring the Python Collection Module: A Guide to Advanced Data Structures
Python Collection Module
The Python collections
module is an essential tool for managing collections of data, providing advanced data structures beyond the basic built-in containers like lists, dictionaries, sets, and tuples. Introduced in Python 2.4, this module aims to enhance the functionality of standard collections, making it easier to work with complex data structures efficiently.
1. namedtuple()
The namedtuple()
function is a subclass of Python’s built-in tuple
, offering a more readable alternative by allowing you to assign names to each field. This makes it easier to access data by name instead of relying on numerical indices, improving code clarity and reducing errors.
Example:
from collections import namedtuple
Person = namedtuple('Person', ['name', 'age', 'gender'])
pranshu = Person('James', 24, 'M')
print(pranshu)
Output:
Person(name='James', age=24, gender='M')
This approach is especially useful when you want to create objects that store simple, immutable data but need more clarity than a traditional tuple offers.
Download New Real Time Projects :-Click here
2. OrderedDict()
An OrderedDict
is a special type of dictionary that maintains the order of items based on their insertion order. While regular dictionaries in older Python versions did not guarantee this order, OrderedDict
provides this feature, making it valuable in situations where the order of data matters.
Example:
from collections import OrderedDict
d1 = OrderedDict()
d1['A'] = 10
d1['C'] = 12
d1['B'] = 11
d1['D'] = 13
for k, v in d1.items():
print(k, v)
Output:
A 10
C 12
B 11
D 13
3. defaultdict()
A defaultdict
is a subclass of the standard dict
class that provides a default value for nonexistent keys. When you try to access a key that doesn’t exist, instead of raising a KeyError
, it automatically assigns a default value of the specified type.
Example:
from collections import defaultdict
number = defaultdict(int)
number['one'] = 1
number['two'] = 2
# Accessing a non-existent key
print(number['three'])
Output:
0
In this example, accessing the key 'three'
returns 0
because we initialized the defaultdict
with the int
type, which defaults to 0
.
https://updategadh.com/category/php-project
4. Counter()
The Counter()
class is a subclass of dict
that counts the occurrences of elements in a collection. It is particularly useful for tasks like frequency analysis, where you need to know how many times each item appears in a list or iterable.
Example:
from collections import Counter
c = Counter([1, 2, 3, 4, 5, 7, 8, 5, 9, 6, 10])
print(c)
Output:
Counter({5: 2, 1: 1, 2: 1, 3: 1, 4: 1, 7: 1, 8: 1, 9: 1, 6: 1, 10: 1})
You can also access individual counts:
print(c[1]) # Output: 1
5. deque()
The deque()
(double-ended queue) class provides a queue-like object that supports fast appends and pops from both ends of the sequence. This is useful when you need a data structure that allows for efficient insertion and removal of items from either side.
Example:
from collections import deque
list_items = ["x", "y", "z"]
deq = deque(list_items)
print(deq)
Output:
deque(['x', 'y', 'z'])
You can easily add or remove items from either end:
deq.appendleft("a") # Adds 'a' to the left side
deq.append("w") # Adds 'w' to the right side
6. ChainMap()
The ChainMap()
class creates a single representation of the data by combining several dictionaries into one group.This can be useful when you need to combine several dictionaries into a single structure without modifying the original dictionaries.
Example:
from collections import ChainMap
baseline = {'Name': 'Peter', 'Age': '14'}
adjustments = {'Age': '15', 'Roll_no': '0012'}
merged = ChainMap(adjustments, baseline)
print(list(merged))
Output:
['Age', 'Name', 'Roll_no']
Here, the ChainMap
combines the adjustments
and baseline
dictionaries, with the values from adjustments
taking precedence over those in baseline
.
7. UserDict()
, UserList()
, and UserString()
The UserDict
, UserList
, and UserString
classes provide wrappers around the built-in Python types dict
, list
, and str
, respectively. These classes make it easy to extend and customize the behavior of these data structures by adding new functionality.
- UserDict: Wraps a dictionary object.
- UserList: Wraps a list object.
- UserString: Wraps a string object.
These classes allow you to define custom behavior while retaining compatibility with standard Python operations.
- python collections w3schools
- Exploring the Python Collection Module
- python collections example
- python collection type
- Exploring the Python Collection Module
- Exploring the Python Collection Module
- Exploring the Python Collection Module
- python collections counter
- import collections python
- collections python install
- python counter
- python deque
- Exploring the Python Collection Module: A Guide to Advanced Data Structures
- Exploring the Python Collection Module
Post Comment