Python: How to get the first/last item from a dictionary

Updated: February 13, 2024 By: Guest Contributor Post a comment

Introduction

Working with dictionaries is a fundamental aspect of programming in Python. They are incredibly versatile, but certain operations, like getting the first or last item, are not immediately straightforward because dictionaries are inherently unordered. However, with the introduction of Python 3.7, dictionaries now maintain insertion order, making it possible to identify the first and last items.

In this detailed guide, we’ll explore how to extract the first and last items from a dictionary in Python. Whether you’re a beginner or have some advanced knowledge, this tutorial aims to provide you with actionable insights and examples that you can easily integrate into your projects.

Basic Examples

Let’s start with the basics and progressively delve into more advanced territory.

Getting the First Item

# Basic method for Python 3.7 and above
dict_example = {'apple': 1, 'banana': 2, 'cherry': 3}
first_key, first_value = list(dict_example.items())[0]
print(first_key, first_value)
# Output: apple 1

Getting the Last Item

# Basic method for Python 3.7 and above
dict_example = {'apple': 1, 'banana': 2, 'cherry': 3}
last_key, last_value = list(dict_example.items())[-1]
print(last_key, last_value)
# Output: cherry 3

Intermediate Level

As we progress, let’s examine some methods that are more efficient or suited for specific scenarios.

Using iter()

# More efficient method using iter()
dict_example = {'apple': 1, 'banana': 2, 'cherry': 3}
first_item = next(iter(dict_example.items()))
print(first_item)
# Output: ('apple', 1)

Using OrderedDict

# For versions below Python 3.7
from collections import OrderedDict
dict_example = OrderedDict([('apple', 1), ('banana', 2), ('cherry', 3)])
first_key, first_value = next(iter(dict_example.items()))
print(first_key, first_value)
# Output: apple 1

Advanced Examples

Let’s explore more complex techniques that could be beneficial in specific contexts or with dictionaries with unique characteristics.

Using Reversed()

# Getting the last item efficiently in Python 3.8 and above
dict_example = {'apple': 1, 'banana': 2, 'cherry': 3}
last_item = next(reversed(dict_example.items()))
print(last_item)
# Output: ('cherry', 3)

Using Custom Functions

In scenarios where you need more control or have very specific requirements, writing a custom function can be the way to go. This method is particularly useful when dealing with large dictionaries or when performance is a concern.

def get_first_item(d):
    return next(iter(d.items()))

def get_last_item(d):
    for item in reversed(d.items()):
        return item

dict_example = {'apple': 1, 'banana': 2, 'cherry': 3}
print(get_first_item(dict_example))
# Output: ('apple', 1)
print(get_last_item(dict_example))
# Output: ('cherry', 3)

Conclusion

In conclusion, while dictionaries in Python do not have built-in methods specifically for retrieving the first or last items due to their unordered nature, the Python language provides multiple ways to achieve this, particularly after versions 3.7 and 3.8 where dictionaries maintain insertion order. By understanding and applying the methods outlined above, you can easily manipulate dictionaries to suit your needs, whether you’re dealing with basic requirements or more complex scenarios.