Sobes.tech
Junior — Middle

What data structures can be used instead of a regular dictionary?.

sobes.tech AI

Answer from AI

Instead of the usual dictionary (dict) in Python, you can use the following data structures:

  • collections.OrderedDict — preserves the order of insertion (this was important before Python 3.7, now a regular dict is also ordered).
  • collections.defaultdict — a dictionary with a default value for missing keys.
  • collections.Counter — a dictionary for counting the number of occurrences of elements.
  • types.MappingProxyType — an immutable (read-only) dictionary.
  • dict with __slots__ or specialized classes for memory optimization.
  • dataclasses or namedtuple — for fixed sets of fields accessible by name.

Example of using defaultdict:

from collections import defaultdict

counts = defaultdict(int)
for word in ['apple', 'banana', 'apple']:
    counts[word] += 1

print(counts)  # defaultdict(<class 'int'>, {'apple': 2, 'banana': 1})