Python Reference ยท Standard Library: Data Structures and Functional Tools
collections.OrderedDict and ChainMap
Reference for collections.OrderedDict and ChainMap: move_to_end, order-sensitive equality, an LRU cache sketch, layered lookups and where writes go.
Since Python 3.7 every dict remembers insertion order, so OrderedDict matters less than it once did. It still has two things a plain dict lacks: move_to_end() and an equality test that cares about order. That makes it a good base for small LRU caches.
ChainMap groups several mappings into one view. Lookups search the maps from first to last; writes only touch the first map. It models layered settings such as "command line, then environment, then defaults".
from collections import OrderedDict, ChainMap od = OrderedDict(a=1, b=2) od.move_to_end("a")
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
OrderedDict(*args, **kwargs) ChainMap(*maps)
| Member | Description |
|---|---|
OrderedDict.move_to_end(key, last=True) |
Move an existing key to the end (or to the front with last=False). Raises KeyError if missing. |
OrderedDict.popitem(last=True) |
Remove and return a (key, value) pair from the end (LIFO) or, with last=False, the front (FIFO). |
ChainMap.maps |
The list of underlying mappings; you may change it. |
ChainMap.new_child(m=None) |
A new chain with m (or an empty dict) placed in front. |
ChainMap.parents |
A new chain without the first map. |
Return value: a new OrderedDict or ChainMap. ChainMap() with no arguments starts with one empty dict.
Raises: KeyError for missing keys. ChainMap deletes (del, pop) also only act on the first map and raise KeyError if the key is not there, even if a later map has it.
Usage notes
- Plain dicts keep order too. Reach for
OrderedDictonly when you needmove_to_end(),popitem(last=False)or order-sensitive equality. - Equality differs.
OrderedDict == OrderedDictcompares order. Comparing anOrderedDictwith a plaindictignores order. - Updating an existing key keeps its position; removing and re-inserting moves it to the end.
ChainMapdoes not copy. Changes made to an underlying map show up immediately, as in the second example. Usedict(chain)for a flat snapshot.- Writes, deletes and
clear()affect onlymaps[0], which is why layering a copy of the defaults under a user dict is safe. - Iteration order of a
ChainMapruns from the last map to the first, with later maps' keys first;len()counts distinct keys. Do not rely on its order. - For real caching prefer
functools.lru_cache; theOrderedDictversion is useful when you need control over keys. - Name lookup scopes (
locals,globals,builtins) behave like a chain of maps, andChainMapis a convenient way to model them.
Related
collectionsmodule,defaultdict,dict.copy()- Lessons: Collections, Dictionaries