Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get last value of an OrderedDict in Python3

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
like image 712
warvariuc Avatar asked Sep 01 '14 07:09

warvariuc


People also ask

How do I get the last item in a dictionary?

To get the last key in a dictionary:Use the dict. keys() method to get a view of the dictionary's keys. Use the list() class to convert the view to a list. Access the list item at index -1 to get the last key.

Is OrderedDict slower than dict?

As you see in the output, operations on dict objects are faster than operations on OrderedDict objects.

Does Python dict preserve order?

Standard dict objects preserve order in the reference (CPython) implementations of Python 3.5 and 3.6, and this order-preserving property is becoming a language feature in Python 3.7.

What is the difference between dict and OrderedDict?

The OrderedDict is a subclass of dict object in Python. The only difference between OrderedDict and dict is that, in OrderedDict, it maintains the orders of keys as inserted. In the dict, the ordering may or may not be happen. The OrderedDict is a standard library class, which is located in the collections module.


2 Answers

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
like image 70
enrico.bacis Avatar answered Oct 04 '22 00:10

enrico.bacis


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)
like image 45
warvariuc Avatar answered Oct 03 '22 22:10

warvariuc