Open In App

Get First N Key:Value Pairs in given Dictionary – Python

Last Updated : 04 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

We are given a dictionary and tasked with retrieving the first N key-value pairs. For example, if we have a dictionary like this: {‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4} and we need the first 2 key-value pairs then the output will be: {‘a’: 1, ‘b’: 2}.

Using itertools.islice()

One of the most efficient ways to get the first N key-value pairs is using itertools.islice() as this function allows you to iterate over a dictionary and slice the first N items without creating a full copy of the dictionary.

Python
from itertools import islice

d1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

# Getting the first 2 key-value pairs
d2 = dict(islice(d1.items(), 2))

print(d2)

Output
{'a': 1, 'b': 2}

Explanation:

  • d1.items() returns the key-value pairs of the dictionary and islice(d1.items(), 2) slices the first 2 key-value pairs from the iterator.
  • We convert the result back into a dictionary using dict().

Using Dictionary Comprehension

Another effective way to get the first N key-value pairs from a dictionary is using dictionary comprehension in which we can iterate over the dictionary and select the first N items based on a condition.

Python
d1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

# Getting the first 2 key-value pairs using dictionary comprehension
d2 = {k: v for i, (k, v) in enumerate(d1.items()) if i < 2}

print(d2)

Output
{'a': 1, 'b': 2}

Explanation:

  • enumerate(d1.items()) adds an index to the key-value pairs of the dictionary, dictionary comprehension iterates over these pairs and checks if the index i is less than the specified limit (2 in this case).
  • This gives us the first N key-value pairs from the dictionary.

Using dict() with list()

This method involves converting the dictionary’s key-value pairs into a list and then slicing it to get the first N key-value pairs, but keep in mind that it creates an intermediate list of all the dictionary items. Hence, for very large dictionaries this could consume more memory than necessary as you’re storing all items temporarily in a list.

Python
d1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

# Getting the first 2 key-value pairs by slicing the list of items
d2 = dict(list(d1.items())[:2])

print(d2)

Output
{'a': 1, 'b': 2}

Explanation:

  • list(d1.items()) converts the dictionary items into a list of tuples.
  • [:2] slices the list to get the first 2 items.
  • dict() converts the sliced list back into a dictionary.

Using a loop

In this method we use a loop to manually extract the first N key-value pairs from a dictionary. This is more verbose but gives you more control over the process such as handling specific conditions or processing the items further.

Python
d1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

# Getting the first 2 key-value pairs using a loop
d2 = {}
for i, (k, v) in enumerate(d1.items()):
    if i < 2:
        d2[k] = v

print(d2)

Output
{'a': 1, 'b': 2}

Explanation:

  • We use enumerate(d1.items()) to loop through the dictionary with an index.
  • The loop continues to add key-value pairs to d2 until the index reaches 2, ensuring only the first 2 pairs are included.
  • This method is useful if you want to perform additional processing during the loop.


Next Article
Practice Tags :

Similar Reads