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
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.
As you see in the output, operations on dict objects are faster than operations on OrderedDict objects.
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.
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.
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With