Saturday, November 16, 2024
Google search engine
HomeLanguagesPython | Get first K items in dictionary

Python | Get first K items in dictionary

While working with dictionaries, we can come across a problem in which we might have to get just some of the initial keys in dictionary. This problem can typically occur in cases of the web development domain. Let’s discuss certain ways in which this problem can be solved.

Method #1 : Using items() + list slicing 

To solve this problem, a combination of the above functions has to be implied. The items function can be used to get all the dictionary items and main task is done by list slicing, which limits the dictionary key-value pair. 

Python3




# Python3 code to demonstrate working of
# Get first K items in dictionary
# Using items() + list slicing
 
# Initialize dictionary
test_dict = {'gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'CS': 5}
 
# printing original dictionary
print("The original dictionary : " + str(test_dict))
 
# Initialize limit
K = 3
 
# Using items() + list slicing
# Get first K items in dictionary
res = dict(list(test_dict.items())[0: K])
 
# printing result
print("Dictionary limited by K is : " + str(res))


Output : 

The original dictionary : {‘is’: 2, ‘CS’: 5, ‘best’: 3, ‘gfg’: 1, ‘for’: 4} Dictionary limited by K is : {‘is’: 2, ‘CS’: 5, ‘best’: 3}

Time Complexity: O(n), where n is the length of the list test_dict
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list

Method #2: Using islice() + items() 

The combination of the above functions can be used to perform this particular task. In these, we perform the slice using the islice() and items function allows us to get the items out of iterable.

Python3




# Python3 code to demonstrate working of
# Get first K items in dictionary
# Using islice() + items()
import itertools
 
# Initialize dictionary
test_dict = {'gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'CS': 5}
 
# printing original dictionary
print("The original dictionary : " + str(test_dict))
 
# Initialize limit
K = 3
 
# Using islice() + items()
# Get first K items in dictionary
res = dict(itertools.islice(test_dict.items(), K))
 
# printing result
print("Dictionary limited by K is : " + str(res))


Output

The original dictionary : {'gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'CS': 5}
Dictionary limited by K is : {'gfg': 1, 'is': 2, 'best': 3}

The time complexity of the provided Python code is O(K), as the itertools.islice() method is used to return only the first K items from the dictionary.

The auxiliary space complexity of the code is also O(K), as the res dictionary is created to store the first K items of the original dictionary. 

Method #3: Using list comprehension

This particular problem can also be solved using list comprehension and a combination of items() and list slicing. In this, list comprehension allows one to write of concise codes and combinations of items() and list slicing is used to perform the task.

Python3




# Python3 code to demonstrate working of
# Get first K items in dictionary
# Using list comprehension
   
# Initialize dictionary
test_dict = {'gfg' : 1, 'is' : 2, 'best' : 3, 'for' : 4, 'CS' : 5}
   
# printing original dictionary
print("The original dictionary : " +  str(test_dict))
   
# Initialize limit
K = 3
   
# Using list comprehension
# Get first K items in dictionary
res = {key: test_dict[key] for key in list(test_dict)[:K]}
       
# printing result
print("Dictionary limited by K is : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy


Output

The original dictionary : {'gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'CS': 5}
Dictionary limited by K is : {'gfg': 1, 'is': 2, 'best': 3}

Time complexity: O(n)
Auxiliary space: O(k)

Method 4:  Using a for loop to iterate over the dictionary keys and values and append them to a new dictionary until K items are reached

Approach:

  1. Initialize a dictionary named “test_dict” with some key-value pairs.
  2. Print the original dictionary using the “print()” function and string concatenation.
  3. Initialize a variable “K” with the number of items to be returned from the dictionary.
  4. Initialize an empty dictionary named “res”.
  5. Use a for loop with “test_dict.items()” to iterate over the key-value pairs of the dictionary.
  6. Check if the length of “res” is less than “K”. If so, add the key-value pair to the “res” dictionary using the key as the index and the value as the value.
  7. If the length of “res” is equal to or greater than “K”, break out of the loop.
  8. Print the final dictionary named “res” limited to the first K items.

Python3




# Python3 code to demonstrate working of
# Get first K items in dictionary
# Using for loop
 
# Initialize dictionary
test_dict = {'gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'CS': 5}
 
# printing original dictionary
print("The original dictionary : " + str(test_dict))
 
# Initialize limit
K = 3
 
# Initialize a new dictionary
res = {}
 
# Using for loop
# Get first K items in dictionary
for key, value in test_dict.items():
    if len(res) < K:
        res[key] = value
    else:
        break
 
# printing result
print("Dictionary limited by K is : " + str(res))


Output

The original dictionary : {'gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'CS': 5}
Dictionary limited by K is : {'gfg': 1, 'is': 2, 'best': 3}

Time complexity: O(n), where n is the number of items in the dictionary. 
Auxiliary space: O(K), where K is the number of items to be returned.

Method #5: Using itertools library and islice() function

Step-by-step approach:

  • Importing the islice() function from the itertools library.
  • Use the islice() function along with the items() function of the dictionary to create a new iterator that returns the first K items of the dictionary.
  • Finally, create a new dictionary res by passing the iterator returned by islice() to the dict() constructor.
  • Print the resulting dictionary res to the console.

Below is the implementation of the above approach:

Python3




# import islice function from itertools library
from itertools import islice
 
# Initialize dictionary
test_dict = {'gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'CS': 5}
 
# printing original dictionary
print("The original dictionary : " + str(test_dict))
 
# Initialize limit
K = 3
 
# Using islice() and items()
# Get first K items in dictionary
res = dict(islice(test_dict.items(), K))
 
# printing result
print("Dictionary limited by K is : " + str(res))


Output

The original dictionary : {'gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'CS': 5}
Dictionary limited by K is : {'gfg': 1, 'is': 2, 'best': 3}

Time complexity: O(K), as we only iterate over K items in the dictionary.
Auxiliary space: O(K) auxiliary space to store the new dictionary res.

RELATED ARTICLES

Most Popular

Recent Comments