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

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

Last updated: February 13, 2024

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.

Next Article: Python: Passing a dictionary as a function argument

Previous Article: Python RuntimeError: directory changed during iteration

Series: Working with Dict, Set, and Tuple in Python

Python

You May Also Like

  • Python Warning: Secure coding is not enabled for restorable state
  • Python TypeError: write() argument must be str, not bytes
  • 4 ways to install Python modules on Windows without admin rights
  • Python TypeError: object of type ‘NoneType’ has no len()
  • Python: How to access command-line arguments (3 approaches)
  • Understanding ‘Never’ type in Python 3.11+ (5 examples)
  • Python: 3 Ways to Retrieve City/Country from IP Address
  • Using Type Aliases in Python: A Practical Guide (with Examples)
  • Python: Defining distinct types using NewType class
  • Using Optional Type in Python (explained with examples)
  • Python: How to Override Methods in Classes
  • Python: Define Generic Types for Lists of Nested Dictionaries
  • Python: Defining type for a list that can contain both numbers and strings
  • Using TypeGuard in Python (Python 3.10+)
  • Python: Using ‘NoReturn’ type with functions
  • Type Casting in Python: The Ultimate Guide (with Examples)
  • Python: Using type hints with class methods and properties
  • Python: Typing a function with default parameters
  • Python: Typing a function that can return multiple types