When working with any type of database, you will come across dictionaries. A dictionary contains key/value pairs and any data type. Dictionaries are simply ordered mapping from keys to values. In Python, dictionaries are mutable structures, meaning they can change their values. On this page, there will be a discussion on various methods to grab the first n items from a dictionary In Python.
* Working on Jupyter Notebook Anaconda Environment.
Method 1: Grab the first n items from a dictionary using the List Comprehension method
The best way to get the first n items from a dictionary in Python is by using the List Comprehension approach. In this method, list comprehension for…in structure is used in aggregation with a list-slicing operator to grab/get the n items from the dictionary.
The execution process executes like this:
The following code will give an example of how to get the first two items from a dictionary in Python:
- You must slice a list to reach a range of elements for list slicing. You can slice a list using the colon “:” operator.
- List built-in function to convert the data type into list format.
- [:2] means 2 indexes will be excluded and start from zero by default. So it includes items from 0-1. The last key/value will be excluded from the results.
#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
{'dish01': 'Thai', 'dish02': 'Moroccan'}
Method 2: iter() and next() function to grab the first n items from a dictionary
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 containing keys/values.
- Using iter() returns the iterated objects.
- 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')
Method 3: Using enumerate () function to gran first n items from a dictionary
Using enumerate function, grabbing the first n items from a dictionary in Python can be possible. A dictionary first n items is retrieved using the for and break iterations in aggregation with enumerate () function.
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.
#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')
Conclusion
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 to access the first n items from a dictionary in Python.
If you want to learn more about Python Programming, Visit Python Programming Tutorials.