summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--Doc/library/collections.rst12
-rw-r--r--Lib/collections.py6
-rw-r--r--Lib/test/test_collections.py7
3 files changed, 20 insertions, 5 deletions
diff --git a/Doc/library/collections.rst b/Doc/library/collections.rst
index d6d1b68..32375a2 100644
--- a/Doc/library/collections.rst
+++ b/Doc/library/collections.rst
@@ -858,8 +858,11 @@ the items are returned in the order their keys were first added.
.. versionadded:: 2.7
-The :meth:`popitem` method for ordered dictionaries returns and removes the
-last added entry. The key/value pairs are returned in LIFO order.
+.. method:: OrderedDict.popitem(last=True)
+
+ The :meth:`popitem` method for ordered dictionaries returns and removes
+ a (key, value) pair. The pairs are returned in LIFO order if *last* is
+ true or FIFO order if false.
Equality tests between :class:`OrderedDict` objects are order-sensitive
and are implemented as ``list(od1.items())==list(od2.items())``.
@@ -867,3 +870,8 @@ Equality tests between :class:`OrderedDict` objects and other
:class:`Mapping` objects are order-insensitive like regular dictionaries.
This allows :class:`OrderedDict` objects to be substituted anywhere a
regular dictionary is used.
+
+.. seealso::
+
+ `Equivalent OrderedDict recipe <http://code.activestate.com/recipes/576693/>`_
+ that runs on Python 2.4 or later.
diff --git a/Lib/collections.py b/Lib/collections.py
index 1193ebf..8c0b426 100644
--- a/Lib/collections.py
+++ b/Lib/collections.py
@@ -30,7 +30,7 @@ class OrderedDict(dict, MutableMapping):
def clear(self):
self.__end = end = []
- end += [None, end, end] # null entry
+ end += [None, end, end] # sentinel node for doubly linked list
self.__map = {} # key --> [key, prev, next]
dict.clear(self)
@@ -61,10 +61,10 @@ class OrderedDict(dict, MutableMapping):
yield curr[0]
curr = curr[1]
- def popitem(self):
+ def popitem(self, last=True):
if not self:
raise KeyError('dictionary is empty')
- key = next(reversed(self))
+ key = next(reversed(self)) if last else next(iter(self))
value = self.pop(key)
return key, value
diff --git a/Lib/test/test_collections.py b/Lib/test/test_collections.py
index f232df4..9e984ba 100644
--- a/Lib/test/test_collections.py
+++ b/Lib/test/test_collections.py
@@ -768,12 +768,19 @@ class TestOrderedDict(unittest.TestCase):
class GeneralMappingTests(mapping_tests.BasicTestMappingProtocol):
type2test = OrderedDict
+ def test_popitem(self):
+ d = self._empty_mapping()
+ self.assertRaises(KeyError, d.popitem)
+
class MyOrderedDict(OrderedDict):
pass
class SubclassMappingTests(mapping_tests.BasicTestMappingProtocol):
type2test = MyOrderedDict
+ def test_popitem(self):
+ d = self._empty_mapping()
+ self.assertRaises(KeyError, d.popitem)
import doctest, collections