How to Get the Last Key or Value in a Python Dictionary
This guide explains how to retrieve the last key or value from a Python dictionary, based on insertion order. Since Python 3.7, standard dictionaries (dict
) preserve insertion order, making this task straightforward. We'll cover the most efficient and Pythonic methods, and briefly mention OrderedDict
for older Python versions.
Getting the Last Key (Python 3.7+)
In Python 3.7 and later, standard dictionaries maintain insertion order. The simplest way to get the last key is to convert the dictionary to a list and access the last element:
my_dict = {
'id': 1,
'name': 'Tom Nolan',
'country': 'Italy'
}
last_key = list(my_dict)[-1] # Most concise and efficient way
print(last_key) # Output: country
print(my_dict[last_key]) # Output: Italy
first_key = list(my_dict)[0]
print(first_key) # Output: id
list(my_dict)
: This creates a list of the dictionary's keys (in insertion order).[-1]
: Accesses the last element of that list.- You can also use the
my_dict.keys()
method to achieve the same result.
Getting the Last Value (Python 3.7+)
Similarly, to get the last value, use my_dict.values()
:
my_dict = {
'id': 1,
'name': 'Tom Nolan',
'country': 'Italy'
}
last_value = list(my_dict.values())[-1]
print(last_value) # Output: Italy
list(my_dict.values())
: Creates a list of the dictionary's values, in insertion order.[-1]
: Accesses the last element of that list.
Getting the Last Key and Value as a Tuple
If you need both the last key and value as a tuple, use my_dict.items()
:
my_dict = {
'id': 1,
'name': 'Tom Nolan',
'country': 'Italy'
}
index = -1 # Index to retrieve the values
key, value = list(my_dict.items())[index]
print(key) # Output: country
print(value) # Output: Italy
- The
my_dict.items()
method gets a view of key-value pairs of the dictionary. - The view is converted to a list of tuples and the last item is unpacked into
key
andvalue
variables.
Handling Empty Dictionaries
The above methods will raise an IndexError
if the dictionary is empty. To handle this gracefully, check for emptiness before accessing the last element:
my_dict = {
'id': 1,
'name': 'Tom Nolan',
'country': 'Italy'
}
if my_dict: # Checks if the dictionary is NOT empty
last_key = list(my_dict)[-1]
print(last_key) # Output: country
else:
print("Dictionary is empty")
# Handle the empty case appropriately
- Check if the dictionary is not empty, before accessing the last key.
Alternatively, you can use the next()
with reversed()
methods:
my_dict = {
'id': 1,
'name': 'Tom Nolan',
'country': 'Italy'
}
last_key = next(reversed(my_dict.keys()), None) # Gets last key, or `None`.
print(last_key) # Output: country
last_value = my_dict[last_key] # Will not throw error if last_key is None
print(last_value) # Output: Italy
reversed(my_dict.keys())
: Creates a reverse iterator over the dictionary's keys.next(..., None)
: Gets the first item from the iterator (which is the last key in insertion order). If the iterator is empty (dictionary is empty), it returnsNone
(the default value). This avoids theStopIteration
error.- This method is less readable.
OrderedDict
(for Python versions before 3.7)
Before Python 3.7, standard dictionaries did not preserve insertion order. If you're using an older Python version (which is strongly discouraged), you need to use collections.OrderedDict
:
from collections import OrderedDict
my_dict = OrderedDict(
[('id', 1), ('name', 'Tom Nolan'), ('country', 'Italy')]
)
last_key = list(my_dict)[-1] # Same approach as with regular dicts
print(last_key) # Output: country
Important: If you're using Python 3.7 or later (which you should be!), you don't need OrderedDict
for this purpose. Standard dict
objects now preserve insertion order.