How to get the last N key-value pairs in a Python dictionary?

Published on Aug. 22, 2023, 12:17 p.m.

To get the last N key-value pairs of a Python dictionary, you can use the list() function to convert the dictionary items to a list, and then use list slicing to get the last N items. Here’s an example:

my_dict = {'A': 3, 'B': 4, 'C': 1, 'D': 2, 'E': 5}

n = 3

last_n_items = dict(list(my_dict.items())[-n:])

print(last_n_items)

This will output the last three key-value pairs of the dictionary:

{'C': 1, 'D': 2, 'E': 5}

Note that the slicing operation returns a list of tuples (key-value pairs), so we need to convert the result back to a dictionary using the dict() function.

If you want to get the last N items without creating a new dictionary, you can just iterate over the sliced items:

my_dict = {'A': 3, 'B': 4, 'C': 1, 'D': 2, 'E': 5}

n = 3

for key, value in list(my_dict.items())[-n:]:
    print(key, value)

This will output the last three key-value pairs of the dictionary:

C 1
D 2
E 5

Tags: