HOW TO GET THE FIRST N ITEMS FROM A DICTIONARY IN PYTHON?

This tutorial demonstrates how to retrieve the first n items from the dictionary in Python. When working with any type of database, you will come across dictionaries. It contains key/value pairs which can be of any data type. Dictionaries are simply ordered mapping from keys to values. In Python, dictionaries are mutable structures that can change their values. On this page, there will be a discussion on various methods to get the first n items from a dictionary In Python.

Using a for loop

Using a for loop to iterate through the dictionary and get the first n items from a dictionary in Python. Here is how the for loop helps to get the first n items from the dictionary. 

Create a dictionary named “wifi_passwords“. Sets a variable “ret_items” equal to the number of items from the dictionary. Create an empty dictionary “nItems“, to store the resulting K items. Afterwards, use a for loop to iterate through the key-value pairs in the “wifi_passwords” dictionary. On each iteration the key-value pair items are added to the nItems dictionary. Check the length of the “nItems dictionary using the len() function. If the length equals “ret_items”, theN terminate the loop. The items stored in the empty dictionary “nItems” are then printed using the print() function.

# without using enumerate function with break function to get first N items in dictionary

# construct a dictionary
wifi_passwords = {
    'xyz': 'pw123',
    'abc': 'pw456',     
    '123': 'pw789'}

# printing original dictionary
print("The original dictionary : \n" + str(wifi_passwords))

print('\n')
# retrieve first 2 items 
ret_items = 2

# Using a for loop to iterate through the dictionary to get first N items in dictionary
nItems = {}
for key, value in wifi_passwords.items():
    nItems[key] = value
    if len(nItems) == ret_items:
        break

# printing result
print("Get first N items in dictionary :  \n" + str(nItems))
Output:
The original dictionary : 
{'xyz': 'pw123', 'abc': 'pw456', '123': 'pw789'}


Get first N items in dictionary :  
{'xyz': 'pw123', 'abc': 'pw456'}

The above example demonstrates how to use a for loop to retrieve the first K items from a dictionary in Python. The for loop uses the assignment operator and the break command to get the first n items from a dictionary in Python.

Using list slicing Method

Another way is to use the slice notation to get the first N items from a dictionary. However, to retrieve the first N items from the dictionary, first of all convert the dictionary items to a list using list() function which can be sliced using the slice notation [0:N]. Lets move towards the example.

Create a dictionary called inventory. Take the number of items to be retrieved as an input from the user and store them in a variable ret_items. The slice notation [0:ret_items] is then used to get the first n items from index 0 (inclusive) to index specified in ret_items (exclusive) of the dictionary. The output list is then converted back to a dictionary using the dict() constructor and is printed using the print() function. The code is given below:

# using list slicing to get first K items in dictionary

# create a dictionary
inventory = {'apple': 80, 'banana': 70, 'orange': 50, 'grape': 30}

ret_items=int(input("Enter the number of items you want to retrieve: "))

# printing original dictionary
print("The original dictionary : \n" + str(inventory))

print('\n')
# get first N items in dictionary
retrieve_nitems = dict(list(inventory.items())[0: ret_items])

# printing result
print("Get first N items in dictionary :  \n" + str(retrieve_nitems))
Output: 
Enter the number of items you want to retrieve: 3
The original dictionary : 
{'apple': 80, 'banana': 70, 'orange': 50, 'grape': 30}


Get first N items in dictionary :  
{'apple': 80, 'banana': 70, 'orange': 50}

You can also use list comprehension for…in structure in combination with a list-slicing operator to get the n items from the dictionary to improve the code readability. You can slice a list using the colon “:” operator. Use a list() function to convert the dictionary into list format. Then using [:N] operator along with list comprehension technique to select the N elements starting from 0 to N-1.

#simple dictionary with key-values
cuisines = {
  "dish01": "Thai",
  "dish02": "Moroccan",
  "dish03": "Turkish"
}
#for..in structure 
first_2items = {i: cuisines[i] for i in list(cuisines)[:2]}
first_2items
Output:
{'dish01': 'Thai', 'dish02': 'Moroccan'}

In some applications, we need the first three sorted items for the dictionary. For this, you can use OrderedDict method from the collections module along with the dictionary comprehension to get the first N items from a dictionary in Python while maintaining the order of the items. 

Suppose you have a dictionary “students_record” consisting of nested dictionaries as values. Create an OrderedDict by calling the sorted() function on the dictionary items and passing the result to the OrderedDict constructor. Then, using dictionary comprehension, we can get the first N items by slicing the keys of the OrderedDict using the list() function and selecting the first N elements.

    from collections import OrderedDict
    
    # create a sample dictionary
    students_record = {
        'Harry': {'grade': 'A', 'e-mail': 'harry@gmail.com'},
        'Smith': {'grade': 'B', 'e-mail': 'smith@gmail.com'},
        'Robert': {'grade': 'C', 'e-mail': 'robert@gmail.com'}
      }
    
    # create an OrderedDict from the dictionary
    rec = OrderedDict(sorted(students_record.items()))
    
    # printing original dictionary
    print("The original dictionary : \n" + str(rec))
    
    # retrieve first 2 items 
    N = int(input("Enter the number of elements you want to retrieve: "));
    
    # get first N items in dictionary
    nItems = {k: rec[k] for k in list(rec)[:N]}
    # printing result
    print("Get first N items in dictionary :  \n" + str(nItems))
    
    Output:
    The original dictionary : 
    OrderedDict([('Harry', {'grade': 'A', 'e-mail': 'harry@gmail.com'}), ('Robert', {'grade': 'C', 'e-mail': 'robert@gmail.com'}), ('Smith', {'grade': 'B', 'e-mail': 'smith@gmail.com'})])
    Enter the number of elements you want to retrieve: 2
    Get first N items in dictionary :  
    {'Harry': {'grade': 'A', 'e-mail': 'harry@gmail.com'}, 'Robert': {'grade': 'C', 'e-mail': 'robert@gmail.com'}}

    Using itertools.islice() Method

    The itertools.islice() method is another approach to retrieve the first n items from a dictionary in Python. This function takes two arguments: an iterable representing the items of the dictionary and the number of items to retrieve.

    Here is how you can get the first n items from a dictionary in Python using itertools() function.

    Create a dictionary called a “menu“. Then create a variable “ret_items” whose value represent the number of items to be retrieved. The items of this dictionary along with ret_items variable is passed to the itertools.islice() method which returns an iterator. Lastly, using the dict() constructor convert it to the dictionary which is printed using the print() function. The code is given below

    # Using itertools.islice() method to get first N items in dictionary
    import itertools
    
    # create a dictionary
    menu = {'spaghetti': 14.99, 'lasagna': 18.99, 'pizza': 10.99}
    
    # printing original dictionary
    print("The original dictionary : \n" + str(menu))
    
    print('\n')
    
    # retrieve first 2 items 
    ret_items = 2
    
    # get first N items in dictionary
    retrieve_nitems = dict(itertools.islice(menu.items(), ret_items))
    
    # printing result
    print("Get first N items in dictionary :  \n" + str(retrieve_nitems))
    
    Output:
    The original dictionary : 
    {'spaghetti': 14.99, 'lasagna': 18.99, 'pizza': 10.99}
    
    
    Get first N items in dictionary :  
    {'spaghetti': 14.99, 'lasagna': 18.99}

    The above example demonstrates how to use the itertools.islice() method to retrieve the first N items from a dictionary in Python.

    Using Iter() and Next() Function

    Iter () function returns the values of iterated objects. Using different loops in Python, you can repeat the returned iterator object. Moreover, this iterable object can also be used to traverse its values.

    Any iterable object traversed with a for loop is internally converted to an iterator object using the iter() method, and then iteration is performed using the next() method.

    The execution process executes in the following manner:

    • Creating a dictionary named cuisines containing keys/values.
    • Using iter() returns the iterated objects. 
    • Moreover, using for …in structure in aggregation with range () function, getting the first n items from a dictionary is possible. 
    • Pass the n items number as an argument in the range () function. 
    • Then, the next() methods print the iterated items in an object. The next() process returns iterable values.
    #simple dictionary with key-values
    cuisines = {
      "dish01": "Thai",
      "dish02": "Moroccan",
      "dish03": "Turkish"
    }
    n_items = iter(cuisines.items())
    for i in range(2):
        print(next(n_items))
    
    ('dish01', 'Thai')
    ('dish02', 'Moroccan')

    Using Enumerate() Function

    Using enumerate function, grabbing the first n items from a dictionary in Python can be possible. However, a dictionary first n items are retrieved using the for and break iterations in aggregation with enumerate () function.

    Moreover, when using enumerate, each value within an object is accompanied by a counter, which facilitates accessing items within the collection.

    The following example reads from index location 0 (by default) until the break call is made at index location 2.  Key number 2 will be excluded, and terminate the process here using break command. 

    #simple dictionary with key-values
    cuisines = {
      "dish01": "Thai",
      "dish02": "Moroccan",
      "dish03": "Turkish"
    }
    for recipe, (i, j) in enumerate(cuisines.items()):
        if recipe == 2:
            break
        print((i, j))
    
    ('dish01', 'Thai')
    ('dish02', 'Moroccan')

    Use the heapq module to grab the first N smallest items considering the dictionary values

    The heapq module retrieves the first K items from a dictionary based on the dictionary values. However, heapq module takes three arguments: n, iterable, and key. 

    • The n argument indicates the number of items to retrieve, 
    • the iterable argument is the dictionary items to search through, 
    • and moreover, the key argument depicts a function to determine the ordering of the items.

    Here is how the heapq module gets the first n items from a dictionary in Python.

    • Defines a dictionary named wifi_passwords and prints it using the print() function.
    • Sets a variable ret_items to 1 to grab the first item from the dictionary.
    • To retrieve the first K items from the dictionary, use the heapq.nsmallest() function that takes three arguments: n, iterable, and key.
    • However, the key argument is a lambda function that grabs the second item (the value of the corresponding second key) in each key-value pair. 
    • Moreover, the n argument is set to ret_items to retrieve the first item from the dictionary.
    • The output variable items contain the first K items from the original dictionary by considering the dictionary values. 
    • However, the dict() constructor creates a new dictionary from these items.
    • The retrieve_n_items dictionary contains the first K items from the original dictionary construct by considering the values and printing using the
      function afterward.
    import heapq
    
    # construct a dictionary
    wifi_passwords = {'xyz': 'pw123',
             'abc': 'pw456',
             '123': 'pw789'}
    
    # printing original dictionary
    print("The original dictionary : \n" + str(wifi_passwords))
    
    print('\n')
    # retrieve first 2 items 
    ret_items = 1
    
    # Use heapq.nsmallest() to grab the first N smallest items based on the dictionary values
    items = heapq.nsmallest(ret_items, wifi_passwords.items(), key=lambda item: item[1])
    
    # Create a dictionary from the first N smallest items
    retrieve_n_items = dict(items)
    
    # printing result
    print("Get first N items in dictionary :  \n" + str(retrieve_n_items))
    
    The original dictionary : 
    {'xyz': 'pw123', 'abc': 'pw456', '123': 'pw789'}
    
    
    Get first N items in dictionary :  
    {'xyz': 'pw123'}

    Using the slicing notation to Get the first key of a Python dict

    Using the slicing notation to grab the first two keys of a dictionary. However, here is how it executes.

    • Consider a dictionary named wifi_passwords, and printing using the print() function.
    • Afterward, use a for loop with list slicing to retrieve the first two keys of the dictionary. 
    • Moreover, on a dictionary, the list() function is called to retrieve a list of keys, which is then sliced using the [0:2] notation to get the first two keys.
    • Lastly, the loop prints the first two keys by iterating through the sliced list and printing each key using the print command.
    # construct a dictionary
    wifi_passwords = {'xyz': 'pw123',
             'abc': 'pw456',
             '123': 'pw789'}
    
    # printing original dictionary
    print("The original dictionary : \n" + str(wifi_passwords))
    
    print('\n')
    for x in list(wifi_passwords)[0:2]:
        print (x)
    
    The original dictionary : 
    {'xyz': 'pw123', 'abc': 'pw456', '123': 'pw789'}
    
    
    xyz
    abc

    using for loop and slice notation to grab the first n items from a dictionary

    A for loop and list slicing approach to retrieve a dictionary’s first n keys and values in Python.

    • Consider a dictionary named wifi_passwords and printed using the print() function.
    • A for loop in aggregation with list slicing to retrieve the first two keys of the dictionary. 
    • Afterward, on a dictionary, the list() function is invoked to get a list of keys, then sliced using the [0:2] notation to get the first two keys.
    • In the last step, the loop prints the first two keys and their corresponding values by iterating through the sliced list, accessing each value with the wifi_passwords[x] command line.
    • Additionally, using the format() method to print the key and value on separate lines.
    # construct a dictionary to retrieve the first n values from the dictionary
    wifi_passwords = {'xyz': 'pw123',
             'abc': 'pw456',
             '123': 'pw789'}
    
    # printing original dictionary
    print("The original dictionary : \n" + str(wifi_passwords))
    
    print('\n')
    for x in list(wifi_passwords)[0:2]:
        print ("key: {} \n value: {} \n".format(x,  wifi_passwords[x]))
    
    The original dictionary : 
    {'xyz': 'pw123', 'abc': 'pw456', '123': 'pw789'}
    
    
    key: xyz 
     value: pw123 
    
    key: abc 
     value: pw456

    Using for…in structure to get the dictionary items

    The below example iterates over the dictionary wifi_passwords using a for..in structure iterated loop, assigning the key-value pairs to the variable k on each iteration. However, the items() method returns an iterated object containing tuples of the dictionary’s key-value pairs.

    # construct a dictionary to retrieve first n items from the dictionary
    wifi_passwords = {'xyz': 'pw123',
             'abc': 'pw456',
             '123': 'pw789'}
    
    # printing original dictionary
    print("The original dictionary : \n" + str(wifi_passwords))
    
    print('\n')
    
    for k in wifi_passwords.items():
        print(k, type(k))
    
    The original dictionary : 
    {'xyz': 'pw123', 'abc': 'pw456', '123': 'pw789'}
    
    
    ('xyz', 'pw123') <class 'tuple'>
    ('abc', 'pw456') <class 'tuple'>
    ('123', 'pw789') <class 'tuple'>

    Conclusion

    However, on this page, there are three methods discussed with example code using iter()…next() function, List Comprehension, and the enumerate() in aggregation with for…in loop structure. Moreover, using functions like itertools.islice(), list slicing, OrderedDict, for loop, heapq module to access the first n items from a dictionary in Python.

    If you want to learn more about Python Programming, Visit Python Programming Tutorials.

    Leave a Comment

    Your email address will not be published. Required fields are marked *