Sobes.tech
Junior — Middle

What different variations of dictionaries exist in Python?

sobes.tech AI

Answer from AI

In Python, there are several variations of dictionaries that differ in functionality and implementation features:

  1. Standard dict — the basic dictionary type that stores key-value pairs. Starting from Python 3.7, dict maintains insertion order.

  2. collections.OrderedDict — a dictionary from the collections module that guarantees the preservation of insertion order in all Python versions (before 3.7, this was important; after 3.7, dict is also ordered).

  3. collections.defaultdict — a dictionary with a default value for missing keys. When accessing a non-existent key, a value is automatically created using the provided function.

  4. collections.ChainMap — combines multiple dictionaries or mappings into one, allowing sequential key lookup across several dictionaries.

  5. types.MappingProxyType — provides a read-only view of a dictionary.

  6. dict with custom classes — you can create your own classes inheriting from dict to extend functionality.

Example of using defaultdict:

from collections import defaultdict

d = defaultdict(int)
d['a'] += 1
print(d)  # defaultdict(<class 'int'>, {'a': 1})