Saturday, November 16, 2024
Google search engine
HomeLanguagesPython | Get first N key:value pairs in given dictionary

Python | Get first N key:value pairs in given dictionary

Given a dictionary, the task is to get N key: value pairs from given dictionary. This type of problem can be useful while some cases, like fetching first N values in web development. Note that the given dictionary is unordered, the first N pairs will not be same here all the time. In case, you need to maintain order in your problem, you can use ordered dictionary. 

Code #1: Using itertools.islice() method 

Python3




# Python program to get N key:value pairs in given dictionary
# using itertools.islice() method
 
import itertools
     
# Initialize dictionary
test_dict = {'Geeks' : 1, 'For':2, 'is' : 3, 'best' : 4, 'for' : 5, 'CS' : 6}
     
# printing original dictionary
print("The original dictionary : " + str(test_dict))
     
# Initialize limit
N = 3
     
# Using islice() + items()
# Get first N items in dictionary
out = dict(itertools.islice(test_dict.items(), N))
         
# printing result
print("Dictionary limited by K is : " + str(out))


Output

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

Time complexity: O(N) where N is the number of items to be retrieved from the dictionary.
Auxiliary space: O(N) 

Code #2: Using slicing on dictionary item list 

Python3




# Python program to get N key:value pairs in given dictionary
# using list slicing
     
# Initialize dictionary
test_dict = {'Geeks' : 1, 'For':2, 'is' : 3, 'best' : 4, 'for' : 5, 'CS' : 6}
     
# printing original dictionary
print("The original dictionary : " + str(test_dict))
     
# Initialize limit
N = 3
     
# Using items() + list slicing
# Get first K items in dictionary
out = dict(list(test_dict.items())[0: N])
         
# printing result
print("Dictionary limited by K is : " + str(out))


Output

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

Time complexity : O(n)
Auxiliary Space: O(n)

Code #3: Using OrderedDict

Python3




# Python program to get N key:value pairs in given dictionary
# using OrderedDict
   
# importing "collections" for Ordereddict
import collections
     
# Initialize dictionary
test_dict = {'Geeks' : 1, 'For':2'is' : 3, 'best' : 4, 'for' : 5, 'CS' : 6}
     
# printing original dictionary
print("The original dictionary : " +  str(test_dict))
     
# Initialize limit
N = 3
     
# Using OrderedDict and items()
# Get first K items in dictionary
out = collections.OrderedDict(list(test_dict.items())[0: N])
         
# printing result 
print("Dictionary limited by K is : " + str(out))
#This code is contributed by Edula Vinay Kumar Reddy


Output

The original dictionary : {'Geeks': 1, 'For': 2, 'is': 3, 'best': 4, 'for': 5, 'CS': 6}
Dictionary limited by K is : OrderedDict([('Geeks', 1), ('For', 2), ('is', 3)])

Time complexity: O(n)
Auxiliary Space: O(n) 

Method #4: Using a dictionary comprehension and zip() function. 

Step-by-step approach:

  1. Initialize dictionary test_dict with some key-value pairs.
  2. Initialize variable N with the desired limit of key-value pairs to extract from the dictionary.
  3. Use a dictionary comprehension with zip() function to extract the first N key-value pairs from the test_dict dictionary.
  4. Assign the resulting dictionary to a variable called out.
  5. Print the value of out.

Below is the implementation of the above approach:

Python3




# Initialize dictionary
test_dict = {'Geeks' : 1, 'For':2'is' : 3, 'best' : 4, 'for' : 5, 'CS' : 6}
 
# printing original dictionary
print("The original dictionary : " + str(test_dict))
 
# Initialize limit
N = 3
 
# Using dictionary comprehension and zip()
# Get first N items in dictionary
out = {k: test_dict[k] for k in list(test_dict)[:N]}
 
# printing result
print("Dictionary limited by K is : " + str(out))


Output

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

Time complexity: O(N), as we only iterate through the first N items of the dictionary. 
Auxiliary space: O(N), as we create a new dictionary with N items.

Method #5: Using a for loop to iterate through the dictionary and break after N items are processed.

Step-by-step approach:

  • Create a for loop to iterate through the original dictionary.
    • Inside the loop, add each key-value pair to the empty dictionary.
    • Check if the length of the new dictionary is equal to N.
    • If it is, break out of the loop.
  • Print the limited dictionary.

Below is the implementation of the above approach:

Python3




# Initialize dictionary
test_dict = {'Geeks' : 1, 'For':2'is' : 3, 'best' : 4, 'for' : 5, 'CS' : 6}
 
# printing original dictionary
print("The original dictionary : " + str(test_dict))
 
# Initialize limit
N = 3
 
# Using a for loop to iterate through the dictionary
# Get first N items in dictionary
out = {}
for key, value in test_dict.items():
    out[key] = value
    if len(out) == N:
        break
 
# printing result
print("Dictionary limited by K is : " + str(out))


Output

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

Time complexity: O(N), as we only iterate through the first N items in the dictionary.
Auxiliary space: O(N), as we need to create a new dictionary to store the limited items.

Method 6:  use the heapq.nsmallest() function

step-by-step approach :

  1. First, the program imports the heapq module, which is a built-in module in Python for heap operations.
  2. The program then initializes a dictionary named test_dict, which contains key-value pairs of strings and integers.
  3. Next, the program initializes a limit N to 3, which is the number of items we want to keep in the final dictionary.
  4. The program then uses the heapq.nsmallest() function to find the first N smallest items based on the dictionary values. The function takes three arguments:
  5. N: the number of items to return
    test_dict.items(): a list of the dictionary’s key-value pairs
    key=lambda item: item[1]: a lambda function that specifies how to sort the dictionary values. In this case, we are sorting by the second item (i.e., the value).
    The program then creates a dictionary named out from the first N smallest items returned by heapq.nsmallest().
  6. Finally, the program prints the result of the limited dictionary out as a string.

Python3




import heapq
 
# Initialize dictionary
test_dict = {'Geeks': 1, 'For': 2, 'is': 3, 'best': 4, 'for': 5, 'CS': 6}
 
# Initialize limit
N = 3
 
# Use heapq.nsmallest() to find the first N smallest items based on the dictionary values
items = heapq.nsmallest(N, test_dict.items(), key=lambda item: item[1])
 
# Create a dictionary from the first N smallest items
out = dict(items)
 
# printing result
print("Dictionary limited by K is : " + str(out))


Output

Dictionary limited by K is : {'Geeks': 1, 'For': 2, 'is': 3}

 Time complexity of O(N log N) since it needs to sort the dictionary values using a heap.
 Auxiliary space of O(N) since it needs to store at most N items in the new dictionary.

RELATED ARTICLES

Most Popular

Recent Comments