Get the Last Key or Value in a Dictionary in Python

avatar
Borislav Hadzhiev

Last updated: Apr 9, 2024
4 min

banner

# Table of Contents

  1. Get the last Key or Value in a dictionary in Python
  2. Get the last Key or Value in a dictionary using dict.keys() and dict.values()
  3. Get the last Key or Value in a dictionary using reversed()
  4. Using the OrderedDict class in Python versions older than 3.7

# Get the last Key or Value in a dictionary in Python

Use the list() class to get the last key in a dictionary, e.g. list(my_dict)[-1].

The list class converts the dictionary to a list of keys where we can access the element at index -1 to get the last key.

main.py
my_dict = { 'id': 1, 'name': 'Bobby Hadz', 'country': 'Belgium' } last_key = list(my_dict)[-1] print(last_key) # ๐Ÿ‘‰๏ธ country print(my_dict[last_key]) # ๐Ÿ‘‰๏ธ Belgium first_key = list(my_dict)[0] print(first_key) # ๐Ÿ‘‰๏ธ id

get last key or value in dictionary

The code for this article is available on GitHub

If you only need the last value, use the dict.values() method instead.

main.py
my_dict = { 'id': 1, 'name': 'Bobby Hadz', 'country': 'Belgium' } last_value = list(my_dict.values())[-1] print(last_value) # ๐Ÿ‘‰๏ธ Belgium print(list(my_dict.values())) # ๐Ÿ‘‰๏ธ [1, 'Bobby Hadz', 'Belgium']

only getting last value using dict values

We used the list() class to get the last key in a dictionary.

The list() class converts the dictionary to a list of keys.

main.py
my_dict = { 'id': 1, 'name': 'Bobby Hadz', 'country': 'Belgium' } print(list(my_dict)) # ๐Ÿ‘‰๏ธ ['id', 'name', 'country']

The last step is to access the list item at index -1.

main.py
my_dict = { 'id': 1, 'name': 'Bobby Hadz', 'country': 'Belgium' } print(list(my_dict)) # ๐Ÿ‘‰๏ธ ['id', 'name', 'country'] last_key = list(my_dict)[-1] print(last_key) # ๐Ÿ‘‰๏ธ country last_value = my_dict[last_key] print(last_value) # ๐Ÿ‘‰๏ธ Belgium

As of Python 3.7, the standard dict class is guaranteed to preserve the order of keys.

Negative indices can be used to count backward, e.g. my_list[-1] returns the last item in the list and my_list[-2] returns the second-to-last item.

Python indexes are zero-based, so the first item in a list has an index of 0, and the last item has an index of -1 or len(my_list) - 1.

# Get the last Key or Value in a dictionary using dict.keys() and dict.values()

You can also use the dict.keys() method explicitly to get the last key in a dictionary.

main.py
my_dict = { 'id': 1, 'name': 'Bobby Hadz', 'country': 'Belgium' } last_key = list(my_dict.keys())[-1] print(last_key) # ๐Ÿ‘‰๏ธ 'country' print(my_dict[last_key]) # ๐Ÿ‘‰๏ธ 'Belgium'

get last key or value in dictionary using keys and values

The code for this article is available on GitHub

If you only need the last value, use the dict.values() method instead.

main.py
my_dict = { 'id': 1, 'name': 'Bobby Hadz', 'country': 'Belgium' } last_value = list(my_dict.values())[-1] print(last_value) # ๐Ÿ‘‰๏ธ Belgium

The dict.keys() method returns a new view of the dictionary's keys.

main.py
my_dict = { 'id': 1, 'name': 'Bobby Hadz', 'country': 'Belgium' } # ๐Ÿ‘‡๏ธ dict_keys(['id', 'name', 'country']) print(my_dict.keys()) # ๐Ÿ‘‡๏ธ ['id', 'name', 'country'] print(list(my_dict.keys()))

The dict_keys object is not subscriptable, so we can't access it at a specific index.

We can convert the object to a list to get around this.

main.py
my_dict = { 'id': 1, 'name': 'Bobby Hadz', 'country': 'Belgium' } last_key = list(my_dict.keys())[-1] print(last_key) # ๐Ÿ‘‰๏ธ 'country'
You don't have to use the my_dict.keys() method in this scenario because you can just pass the dictionary to the list() class to get a list of its keys.

However, you'll often see this approach being used to get the last key in a dictionary.

# Get the last Key or Value in a dictionary using reversed()

Alternatively, you can use the reversed() function:

  1. Get an iterator of the dictionary's keys and reverse it.
  2. Use the next() function to get the first key from the reversed iterator.
main.py
my_dict = { 'id': 1, 'name': 'Bobby Hadz', 'country': 'Belgium' } last_key = next(reversed(my_dict.keys()), None) print(last_key) # ๐Ÿ‘‰๏ธ country last_value = my_dict[last_key] print(last_value) # ๐Ÿ‘‰๏ธ Belgium

get last key or value in dictionary using reversed

The code for this article is available on GitHub

If you only need the last value, use the dict.values() method.

main.py
my_dict = { 'id': 1, 'name': 'Bobby Hadz', 'country': 'Belgium' } last_value = next(reversed(my_dict.values()), None) print(last_value) # ๐Ÿ‘‰๏ธ Belgium

The reversed() function takes an iterator, reverses it and returns the result.

main.py
result = list(reversed(range(1, 11))) print(result) # ๐Ÿ‘‰๏ธ [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

The next() function returns the next item from the provided iterator.

The function can be passed a default value as the second argument.

If the iterator is exhausted or empty, the default value is returned.

We used None as the default value, so if the dictionary is empty, None is returned.

main.py
my_dict = {} last_key = next(reversed(my_dict.keys()), None) print(last_key) # ๐Ÿ‘‰๏ธ None if last_key is not None: print(my_dict[last_key])

If the iterator is exhausted or empty and no default value is provided, a StopIteration exception is raised.

# Using the OrderedDict class in Python versions older than 3.7

If you use a version older than Python 3.7, then the order of the keys in a dictionary is not preserved and you have to use an OrderedDict.

main.py
from collections import OrderedDict my_dict = OrderedDict( [('id', 1), ('name', 'Bobby Hadz'), ('country', 'Belgium')] ) last_key = list(my_dict)[-1] print(last_key) # ๐Ÿ‘‰๏ธ 'country'

The list() class can also be used to convert the keys of an OrderedDict to a list.

main.py
from collections import OrderedDict my_dict = OrderedDict( [('id', 1), ('name', 'Bobby Hadz'), ('country', 'Belgium')] ) print(list(my_dict)) # ๐Ÿ‘‰๏ธ ['id', 'name', 'country']
The code for this article is available on GitHub

The last step is to access the key at index -1 to get the last key.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev