Get last OrderedDict value in Python3

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

I need to get the last OrderedDict value in Python3 without converting 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

      

+3


source to share


1 answer


Just use this 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

      

+3


source







All Articles