Skip to content

Commit 26aba29

Browse files
authored
Update dict/OrderedDict differences with code equivalents. (GH-31563)
1 parent 8ddbdd9 commit 26aba29

File tree

1 file changed

+23
-6
lines changed

1 file changed

+23
-6
lines changed

Doc/library/collections.rst

Lines changed: 23 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1092,18 +1092,35 @@ Some differences from :class:`dict` still remain:
10921092
Space efficiency, iteration speed, and the performance of update
10931093
operations were secondary.
10941094

1095-
* Algorithmically, :class:`OrderedDict` can handle frequent reordering
1096-
operations better than :class:`dict`. This makes it suitable for tracking
1097-
recent accesses (for example in an `LRU cache
1098-
<https://medium.com/@krishankantsinghal/my-first-blog-on-medium-583159139237>`_).
1095+
* The :class:`OrderedDict` algorithm can handle frequent reordering operations
1096+
better than :class:`dict`. As shown in the recipes below, this makes it
1097+
suitable for implementing various kinds of LRU caches.
10991098

11001099
* The equality operation for :class:`OrderedDict` checks for matching order.
11011100

1101+
A regular :class:`dict` can emulate the order sensitive equality test with
1102+
``p == q and all(k1 == k2 for k1, k2 in zip(p, q))``.
1103+
11021104
* The :meth:`popitem` method of :class:`OrderedDict` has a different
11031105
signature. It accepts an optional argument to specify which item is popped.
11041106

1105-
* :class:`OrderedDict` has a :meth:`move_to_end` method to
1106-
efficiently reposition an element to an endpoint.
1107+
A regular :class:`dict` can emulate OrderedDict's ``od.popitem(last=True)``
1108+
with ``d.popitem()`` which is guaranteed to pop the rightmost (last) item.
1109+
1110+
A regular :class:`dict` can emulate OrderedDict's ``od.popitem(last=False)``
1111+
with ``(k := next(iter(d)), d.pop(k))`` which will return and remove the
1112+
leftmost (first) item if it exists.
1113+
1114+
* :class:`OrderedDict` has a :meth:`move_to_end` method to efficiently
1115+
reposition an element to an endpoint.
1116+
1117+
A regular :class:`dict` can emulate OrderedDict's ``od.move_to_end(k,
1118+
last=True)`` with ``d[k] = d.pop(k)`` which will move the key and its
1119+
associated value to the rightmost (last) position.
1120+
1121+
A regular :class:`dict` does not have an efficient equivalent for
1122+
OrderedDict's ``od.move_to_end(k, last=False)`` which moves the key
1123+
and its associated value to the leftmost (first) position.
11071124

11081125
* Until Python 3.8, :class:`dict` lacked a :meth:`__reversed__` method.
11091126

0 commit comments

Comments
 (0)