6

Here is way to get the last key of an OrderedDict in Python3.

I need to get last value of an OrderedDict in Python3 without conversions to list.

Python 3.4.0 (default, Apr 11 2014, 13:05:11) 

>>> from collections import OrderedDict
>>> dd = OrderedDict(a=1, b=2)
>>> next(reversed(dd))
'b'

>>> next(reversed(dd.keys()))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: argument to reversed() must be a sequence

>>> next(reversed(dd.items()))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: argument to reversed() must be a sequence

>>> next(reversed(dd.values()))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: argument to reversed() must be a sequence
warvariuc
  • 57,116
  • 41
  • 173
  • 227

2 Answers2

7

Just use that key to index the dictionary:

dd[next(reversed(dd))]

For example:

from collections import OrderedDict
dd = OrderedDict(a=1, b=2)
print(dd[next(reversed(dd))])     # 2
enrico.bacis
  • 30,497
  • 10
  • 86
  • 115
2

This was fixed in Python 3.8 (https://bugs.python.org/issue33462).

>>> from collections import OrderedDict
>>> dd = OrderedDict(a=1, b=2)
>>> next(reversed(dd.keys()))
'b'
>>> next(reversed(dd.values()))
2
>>> next(reversed(dd.items()))
('b', 2)
warvariuc
  • 57,116
  • 41
  • 173
  • 227