Collections and Structures
Built-in collections and the collections module for everyday data shaping. Results appear in the same fence: same-line # when short, multiline # blocks below the sample when not.
Busca en todas las páginas de la documentación
Built-in collections and the collections module for everyday data shaping. Results appear in the same fence: same-line # when short, multiline # blocks below the sample when not.
get returns a default; setdefault inserts if missing.
counts: dict[str, int] = {}
counts["a"] = counts.get("a", 0) + 1 # counts == {'a': 1}
counts.setdefault("b", 0) # 0; counts == {'a': 1, 'b': 0}
counts.get("z", -1) # -1Merge mappings with | (3.9+) without mutating inputs.
defaults = {"host": "localhost", "port": 80}
overrides = {"port": 8080}
defaults | overrides
# {'host': 'localhost', 'port': 8080}
defaults # {'host': 'localhost', 'port': 80} (unchanged)Sets support union, intersection, difference, and membership tests.
a, b = {1, 2, 3}, {3, 4}
a | b # {1, 2, 3, 4}
a & b # {3}
a - b # {1, 2}
2 in a # TrueShallow copies via slicing or list.copy() - nested objects still shared.
items = [1, [2], 3]
copy = items[:] # [1, [2], 3]
copy[1] is items[1] # True (shallow)
items.copy() == items # TrueSpecialized dicts from collections reduce boilerplate counting and grouping.
from collections import defaultdict, Counter
groups: defaultdict[str, list[str]] = defaultdict(list)
groups["admin"].append("Ada") # groups['admin'] == ['Ada']
Counter("abracadabra")["a"] # 5Build lists declaratively; keep them readable - extract helpers when complex.
users = [{"id": 1, "active": True}, {"id": 2, "active": False}]
[u["id"] for u in users if u["active"]] # [1]Build dicts from iterables in one expression.
users = [{"id": "u1", "name": "Ada"}, {"id": "u2", "name": "Bob"}]
{u["id"]: u["name"] for u in users} # {'u1': 'Ada', 'u2': 'Bob'}Deduplicate while transforming.
emails = ["a@x.com", "b@y.com", "c@x.com"]
{e.split("@")[1] for e in emails} # {'x.com', 'y.com'}Tuples are immutable sequences - good for keys and fixed records.
point = (10, 20)
point[0] # 10
# point[0] = 1 # TypeError
{(1, 2): "ok"} # {(1, 2): 'ok'}Lightweight records - prefer dataclasses for mutability and defaults.
from dataclasses import dataclass
@dataclass
class User:
id: str
name: str
User("1", "Ada") # User(id='1', name='Ada')Append/pop from both ends in O(1) with deque.
from collections import deque
q: deque[str] = deque()
q.append("a")
q.appendleft("b") # deque(['b', 'a'])
q.pop() # 'a'Maintain a sorted list with the bisect module.
import bisect
xs = [1, 3, 5]
bisect.insort(xs, 4)
xs # [1, 3, 4, 5]Priority queues and top-k selection with heapq.
import heapq
heapq.nlargest(3, [1, 9, 3, 7, 2]) # [9, 7, 3]
heapq.nsmallest(2, [1, 9, 3, 7, 2]) # [1, 2]Look up keys across multiple mappings without merging eagerly.
from collections import ChainMap
cfg = ChainMap({"port": 9}, {"port": 80, "host": "x"})
cfg["port"] # 9
cfg["host"] # 'x'Copy nested structures with copy.deepcopy when sharing is wrong.
import copy
tree = {"kids": [{"n": 1}]}
clone = copy.deepcopy(tree)
clone["kids"][0] is tree["kids"][0] # FalseStack versions: Python 3.14.0 (stable 3.14, maintenance 3.13) · uv 0.6+ · ruff 0.9+
Revisado por Chris St. John·Última actualización: 31 jul 2026