]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
Update dict/OrderedDict differences with code equivalents. (GH-31563)
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Fri, 25 Feb 2022 15:15:58 +0000 (07:15 -0800)
committerGitHub <noreply@github.com>
Fri, 25 Feb 2022 15:15:58 +0000 (07:15 -0800)
(cherry picked from commit 26aba295a9c1bcb0812fe44bd7e68ddd1d8a6828)

Co-authored-by: Raymond Hettinger <rhettinger@users.noreply.github.com>
Doc/library/collections.rst

index c45d90cbbc1c74ebae6a37e6bde1d61519f5e43a..67b64ddda7a2ca1e2d1510d270724b0bcb17da33 100644 (file)
@@ -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
-  <https://medium.com/@krishankantsinghal/my-first-blog-on-medium-583159139237>`_).
+* 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.