Site Tools


import-collections

import collections

import collections is a Python import that provides specialized container types: Counter, defaultdict, OrderedDict, namedtuple, and deque. Use these when the standard dict, list, and tuple don't fit your use case.

Example

# Python
# description: count elements, use defaultdict, create namedtuple
 
from collections import Counter, defaultdict, namedtuple
 
# Count occurrences
words = ["apple", "banana", "apple", "cherry", "apple"]
counts = Counter(words)
print(counts["apple"])  # 3
print(counts.most_common(2))  # [('apple', 3), ('banana', 1)]
 
# Default values for missing keys
graph = defaultdict(list)
graph["a"].append("b")
graph["b"].append("a")
 
# Immutable named tuple
Point = namedtuple("Point", ["x", "y"])
p = Point(10, 20)
print(p.x, p.y)  # 10 20

Common types

  • Counter: count hashable items
  • defaultdict: dict with default value for missing keys
  • OrderedDict: dict that remembers insertion order (Python 3.7+ makes this default)
  • namedtuple: immutable tuple with named fields
  • deque: double-ended queue, efficient insertion at both ends
import-collections.md · Last modified: by 127.0.0.1