- Python Features
- Python Installation
- PyCharm Configuration
- Python Variables
- Python Data Types
- Python If Else
- Python Loops
- Python Strings
- Python Lists
- Python Tuples
- Python List Vs Tuple
- Python Sets
- Python Dictionary
- Python Functions
- Python Files I/O
- Read Write Excel
- Read Write JSON
- Read Write CSV
- Python OS Module
- Python Exceptions
- Python Datetime
- Python Collection Module
- Python Sys Module
- Python Decorator
- Python Generators
- Python OOPS
- Python Numpy Module
- Python Pandas Module
- Python Sqlite Module
Collections Methods with Examples
- namedtuple() – Create Named Tuples:
The namedtuple() function creates a new subclass of tuple with named fields, enhancing code clarity.
from collections import namedtuple
Person = namedtuple('Person', ['name', 'age'])
person = Person('Alice', 30)
print(person.name, person.age)
- Counter() – Count Elements in an Iterable:
The Counter() function creates a dictionary-like object to count occurrences of elements in an iterable.
from collections import Counter
colors = ['red', 'blue', 'red', 'green', 'blue', 'blue']
color_counter = Counter(colors)
print(color_counter['red']) # Output: 2
- deque() – Double-Ended Queue:
The deque() function creates a double-ended queue, useful for fast appends and pops from both ends.
from collections import deque
queue = deque([1, 2, 3])
queue.append(4)
queue.popleft()
print(queue) # Output: deque([2, 3, 4])
- defaultdict() – Default Values for Missing Keys:
The defaultdict() function creates dictionaries with default values for missing keys.
from collections import defaultdict
grades = defaultdict(lambda: 'Not Available')
grades['Alice'] = 95
print(grades['Bob']) # Output: Not Available
- OrderedDict() – Ordered Dictionary:
The OrderedDict() function creates dictionaries that remember the order of insertion.
from collections import OrderedDict
ordered_dict = OrderedDict()
ordered_dict['a'] = 1
ordered_dict['b'] = 2
print(list(ordered_dict.keys())) # Output: ['a', 'b']
- ChainMap() – Chain Multiple Dictionaries:
The ChainMap() function combines multiple dictionaries into a single view.
from collections import ChainMap
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
combined = ChainMap(dict1, dict2)
print(combined['b']) # Output: 2