From 26aba295a9c1bcb0812fe44bd7e68ddd1d8a6828 Mon Sep 17 00:00:00 2001 From: Raymond Hettinger Date: Fri, 25 Feb 2022 08:49:53 -0600 Subject: [PATCH] Update dict/OrderedDict differences with code equivalents. (GH-31563) --- Doc/library/collections.rst | 29 +++++++++++++++++++++++------ 1 file changed, 23 insertions(+), 6 deletions(-) diff --git a/Doc/library/collections.rst b/Doc/library/collections.rst index c45d90cbbc1..67b64ddda7a 100644 --- a/Doc/library/collections.rst +++ b/Doc/library/collections.rst @@ -1092,18 +1092,35 @@ Some differences from :class:`dict` still remain: Space efficiency, iteration speed, and the performance of update operations were secondary. -* Algorithmically, :class:`OrderedDict` can handle frequent reordering - operations better than :class:`dict`. This makes it suitable for tracking - recent accesses (for example in an `LRU cache - `_). +* The :class:`OrderedDict` algorithm can handle frequent reordering operations + better than :class:`dict`. As shown in the recipes below, this makes it + suitable for implementing various kinds of LRU caches. * The equality operation for :class:`OrderedDict` checks for matching order. + A regular :class:`dict` can emulate the order sensitive equality test with + ``p == q and all(k1 == k2 for k1, k2 in zip(p, q))``. + * The :meth:`popitem` method of :class:`OrderedDict` has a different signature. It accepts an optional argument to specify which item is popped. -* :class:`OrderedDict` has a :meth:`move_to_end` method to - efficiently reposition an element to an endpoint. + A regular :class:`dict` can emulate OrderedDict's ``od.popitem(last=True)`` + with ``d.popitem()`` which is guaranteed to pop the rightmost (last) item. + + A regular :class:`dict` can emulate OrderedDict's ``od.popitem(last=False)`` + with ``(k := next(iter(d)), d.pop(k))`` which will return and remove the + leftmost (first) item if it exists. + +* :class:`OrderedDict` has a :meth:`move_to_end` method to efficiently + reposition an element to an endpoint. + + A regular :class:`dict` can emulate OrderedDict's ``od.move_to_end(k, + last=True)`` with ``d[k] = d.pop(k)`` which will move the key and its + associated value to the rightmost (last) position. + + A regular :class:`dict` does not have an efficient equivalent for + OrderedDict's ``od.move_to_end(k, last=False)`` which moves the key + and its associated value to the leftmost (first) position. * Until Python 3.8, :class:`dict` lacked a :meth:`__reversed__` method.