Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Standard library & toolingMiddleCommonPractical

What problems do `collections.defaultdict`, `Counter` and `deque` each solve compared to a plain `dict` or `list`?

Answer

`defaultdict(list)` removes the need to check whether a key exists before appending to it, since accessing a missing key automatically creates it using the supplied factory function instead of raising `KeyError`. `Counter` is a specialized dict for tallying hashable items, giving you `.most_common(n)` and arithmetic between counters for free instead of writing manual counting loops. `deque` (double-ended queue) gives O(1) appends and pops from *both* ends, unlike a plain `list`, whose `insert(0, x)` or `pop(0)` are O(n) because every remaining element has to shift.

Strong answer includes

  • defaultdict auto-creates missing keys via a factory, no existence check needed
  • Counter tallies hashable items with most_common() and counter arithmetic
  • deque gives O(1) operations at both ends, unlike list's O(n) at the front

Practical example

Python example
groups = defaultdict(list)
for item in items:
    groups[item.category].append(item)

groups items by category in three lines, with no

Python example
if category not in groups:

boilerplate.

#collections#data-structures

Sources

collections — Container datatypesPython Software Foundation · deque, defaultdict, Counter, namedtuple and ChainMap semantics