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

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

To get the first N key-value pairs of a Python dictionary, you can use dictionary slicing along with the list() function to convert the result back to a dictionary. Here’s an example:

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

n = 3

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

print(first_n_items)

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

{'A': 3, 'B': 4, 'C': 1}

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.

Alternatively, you can use a loop to iterate over the dictionary items and populate a new dictionary with the first N items:

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

n = 3

first_n_items = dict()

for i, (key, value) in enumerate(my_dict.items()):
    if i < n:
        first_n_items[key] = value
    else:
        break

print(first_n_items)

This will produce the same output as the previous example.

Tags: