diff options
author | Serhiy Storchaka <storchaka@gmail.com> | 2014-04-04 12:19:36 (GMT) |
---|---|---|
committer | Serhiy Storchaka <storchaka@gmail.com> | 2014-04-04 12:19:36 (GMT) |
commit | 578c9211d6b57bbb3cc00ba6dd55893814168695 (patch) | |
tree | 8bc9cf712977f0a6d3778d5c31b8dad4a4422a98 /Lib | |
parent | 3d1e2e4cbb2033344128727bbbbe897bcf9fedfd (diff) | |
download | cpython-578c9211d6b57bbb3cc00ba6dd55893814168695.zip cpython-578c9211d6b57bbb3cc00ba6dd55893814168695.tar.gz cpython-578c9211d6b57bbb3cc00ba6dd55893814168695.tar.bz2 |
Issue #19505: The items, keys, and values views of OrderedDict now support
reverse iteration using reversed().
Diffstat (limited to 'Lib')
-rw-r--r-- | Lib/collections/__init__.py | 33 | ||||
-rw-r--r-- | Lib/test/test_collections.py | 5 |
2 files changed, 35 insertions, 3 deletions
diff --git a/Lib/collections/__init__.py b/Lib/collections/__init__.py index d6deb6a..3605cc3 100644 --- a/Lib/collections/__init__.py +++ b/Lib/collections/__init__.py @@ -20,6 +20,23 @@ from reprlib import recursive_repr as _recursive_repr ### OrderedDict ################################################################################ +class _OrderedDictKeysView(KeysView): + + def __reversed__(self): + yield from reversed(self._mapping) + +class _OrderedDictItemsView(ItemsView): + + def __reversed__(self): + for key in reversed(self._mapping): + yield (key, self._mapping[key]) + +class _OrderedDictValuesView(ValuesView): + + def __reversed__(self): + for key in reversed(self._mapping): + yield self._mapping[key] + class _Link(object): __slots__ = 'prev', 'next', 'key', '__weakref__' @@ -162,9 +179,19 @@ class OrderedDict(dict): return size update = __update = MutableMapping.update - keys = MutableMapping.keys - values = MutableMapping.values - items = MutableMapping.items + + def keys(self): + "D.keys() -> a set-like object providing a view on D's keys" + return _OrderedDictKeysView(self) + + def items(self): + "D.items() -> a set-like object providing a view on D's items" + return _OrderedDictItemsView(self) + + def values(self): + "D.values() -> an object providing a view on D's values" + return _OrderedDictValuesView(self) + __ne__ = MutableMapping.__ne__ __marker = object() diff --git a/Lib/test/test_collections.py b/Lib/test/test_collections.py index ee28a6c..d352d2a 100644 --- a/Lib/test/test_collections.py +++ b/Lib/test/test_collections.py @@ -1187,6 +1187,11 @@ class TestOrderedDict(unittest.TestCase): self.assertEqual(list(od.items()), pairs) self.assertEqual(list(reversed(od)), [t[0] for t in reversed(pairs)]) + self.assertEqual(list(reversed(od.keys())), + [t[0] for t in reversed(pairs)]) + self.assertEqual(list(reversed(od.values())), + [t[1] for t in reversed(pairs)]) + self.assertEqual(list(reversed(od.items())), list(reversed(pairs))) def test_popitem(self): pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] |