Python & SQL BibleChapter 54
5.4 Python's Collections Module
Section 4 of 6-~ 12 min read-Synced from Cuantum content
Python's collections module is a great resource for developers looking to work with different data structures. In addition to the built-in ones, the module offers a variety of specialized data structures that can help optimize performance and simplify code.
For example, the defaultdict class is a subclass of the built-in dict class that automatically initializes missing keys with a default value. Another useful data structure is the Counter class, which allows you to count occurrences of items in a list or other iterable. By taking advantage of these additional data structures, developers can write more efficient and effective code.
Here's a brief introduction:
- Counter: A dict subclass for counting hashable objects.
from collections import Counterc = Counter('hello world')print(c) # Outputs: Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1})- defaultdict: A dict subclass that calls a factory function to supply missing values.
from collections import defaultdictd = defaultdict(int)d['missing']print(d) # Outputs: defaultdict(<class 'int'>, {'missing': 0})- OrderedDict: A dict subclass that remembers the order entries were added.
from collections import OrderedDictd = OrderedDict()d['a'] = 1d['b'] = 2print(d) # Outputs: OrderedDict([('a', 1), ('b', 2)])- deque: A list-like container with fast appends and pops on either end.
from collections import dequed = deque()d.append('a')d.append('b')print(d) # Outputs: deque(['a', 'b'])- namedtuple: Generates subclasses of tuple with named fields.
from collections import namedtuplePoint = namedtuple('Point', ['x', 'y'])p = Point(1, y=2)print(p) # Outputs: Point(x=1, y=2)