Get First N Key:Value Pairs in given Dictionary - Python
Last Updated :
04 Feb, 2025
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)
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)
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)
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)
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.
Similar Reads
Get the number of keys with given value N in dictionary - Python Our task is to count how many keys have a specific value n in a given dictionary. For example, in: data = {'a': 5, 'b': 3, 'c': 5, 'd': 7, 'e': 5} and n = 5. The keys 'a', 'c', and 'e' have the value 5 so the output should be 3.Using Counter from collectionsWe count occurrences of each value using C
2 min read
Python - Key Value list pairings in Dictionary Sometimes, while working with Python dictionaries, we can have problems in which we need to pair all the keys with all values to form a dictionary with all possible pairings. This can have application in many domains including day-day programming. Lets discuss certain ways in which this task can be
7 min read
Get first K items in dictionary = Python We are given a dictionary and a number K, our task is to extract the first K key-value pairs. This can be useful when working with large dictionaries where only a subset of elements is needed. For example, if we have: d = {'a': 1, 'b': 2, 'c': 3, 'd': 4} and K = 2 then the expected output would be:
2 min read
Python Iterate Dictionary Key, Value In Python, a Dictionary is a data structure that stores the data in the form of key-value pairs. It is a mutable (which means once created we modify or update its value later on) and unordered data structure in Python. There is a thing to keep in mind while creating a dictionary every key in the dic
3 min read
Get Index of Values in Python Dictionary Dictionary values are lists and we might need to determine the position (or index) of each element within those lists. Since dictionaries themselves are unordered (prior to Python 3.7) or ordered based on insertion order (in Python 3.7+), the concept of "index" applies to the valuesâspecifically whe
3 min read
Get Total Keys in Dictionary - Python We are given a dictionary and our task is to count the total number of keys in it. For example, consider the dictionary: data = {"a": 1, "b": 2, "c": 3, "d": 4} then the output will be 4 as the total number of keys in this dictionary is 4.Using len() with dictThe simplest way to count the total numb
2 min read