Python collections Module
×


Python collections Module

269

Python collections Module in Python

Introduction to Python collections Module

Python's collections module offers a set of specialized container datatypes that extend the functionality of built-in types like lists, tuples, and dictionaries. These tools provide efficient solutions for common programming tasks, enhancing code readability and performance.

Counter

The Counter class is a dictionary subclass designed to count hashable objects. It tallies the number of occurrences of each element in an iterable, making it useful for tasks like frequency analysis.

from collections import Counter

elements = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
counter = Counter(elements)
print(counter)

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

OrderedDict

An OrderedDict maintains the order in which keys are inserted. While regular dictionaries preserve insertion order in Python 3.7 and above, OrderedDict offers additional methods that can be beneficial in certain scenarios.

from collections import OrderedDict

ordered_dict = OrderedDict()
ordered_dict['one'] = 1
ordered_dict['two'] = 2
ordered_dict['three'] = 3

for key, value in ordered_dict.items():
    print(key, value)

defaultdict

The defaultdict class provides a default value for keys that don't exist in the dictionary. This eliminates the need to check for key existence before assignment.

from collections import defaultdict

def default_value():
    return 'Not Present'

d = defaultdict(default_value)
d['a'] = 1
print(d['a'])       # Output: 1
print(d['b'])       # Output: Not Present

ChainMap

ChainMap groups multiple dictionaries into a single view. It searches through the dictionaries in the order they are provided, returning the first matching key found.

from collections import ChainMap

dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
chain = ChainMap(dict1, dict2)
print(chain['b'])   # Output: 2
print(chain['c'])   # Output: 4

namedtuple

namedtuple creates tuple subclasses with named fields, allowing for more readable and self-documenting code. Fields can be accessed by name instead of position.

from collections import namedtuple

Point = namedtuple('Point', ['x', 'y'])
p = Point(10, 20)
print(p.x, p.y)     # Output: 10 20

deque

A deque (double-ended queue) supports adding and removing elements from both ends with approximately equal efficiency. It's ideal for implementing queues and stacks.

from collections import deque

d = deque()
d.append(1)
d.appendleft(2)
print(d)            # Output: deque([2, 1])
d.pop()
d.popleft()
print(d)            # Output: deque([])

UserDict, UserList, and UserString

These classes act as wrappers around their respective built-in types, allowing for easier subclassing and customization.

  • UserDict: Wraps a dictionary for easier subclassing.
  • UserList: Wraps a list for easier subclassing.
  • UserString: Wraps a string for easier subclassing.
from collections import UserDict

class MyDict(UserDict):
    def __setitem__(self, key, value):
        super().__setitem__(key, value*2)

d = MyDict()
d['a'] = 2
print(d)            # Output: {'a': 4}

Conclusion

The collections module in Python enriches the standard data types with additional functionalities, making it easier to write efficient and readable code. By leveraging these specialized containers, developers can handle complex data structures with greater ease and clarity.



If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!

For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments

Coding Tag WhatsApp Chat