Python Collections


Data Types

ChainMap

To combine mappings in a manner that preserves values hierarchically, consider using a ChainMap.

The list of mappings is stored internally. Lookups traverse the entire list (in order) until a match is found, while deletions, insertions, and updates only operate on the first mapping.

A simple example would be the Python interpreter's own lookup chain:

import builtins
from collections import ChainMap

pylookup = ChainMap(locals(), globals(), vars(builtins))

To add a new lowest-priority mapping to an existing ChainMap, update the maps list directly.

from collections import ChainMap

inventory = ChainMap(store_inventory, regional_inventory)
inventory.maps.append(global_inventory)

To add a new highest-priority mapping to an existing ChainMap, instead create a new object with the new_child() method.

merchandise = inventory.new_child(showroom_inventory)

A ChainMap is much faster than a series of update() calls on a single dictionary, while still offering an ordering of keys that matches such an implementation.

In the context of type annotations, try:

from collections import ChainMap

c: ChainMap[str, int] = ChainMap({"table": 1, "chair": 4})

Counter

Deque

DefaultDict

NamedTuple

OrderedDict

UserDict

UserList

UserString


Abstract Base Classes

See here for details.


CategoryRicottone