Python | Get first K items in dictionary
Last Updated :
27 Apr, 2023
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
test_dict = {'gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'CS': 5}
print("The original dictionary : " + str(test_dict))
K = 3
res = dict(list(test_dict.items())[0: K])
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
import itertools
test_dict = {'gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'CS': 5}
print("The original dictionary : " + str(test_dict))
K = 3
res = dict(itertools.islice(test_dict.items(), K))
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
test_dict = {'gfg' : 1, 'is' : 2, 'best' : 3, 'for' : 4, 'CS' : 5}
print("The original dictionary : " + str(test_dict))
K = 3
res = {key: test_dict[key] for key in list(test_dict)[:K]}
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)
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:
- Initialize a dictionary named “test_dict” with some key-value pairs.
- Print the original dictionary using the “print()” function and string concatenation.
- Initialize a variable “K” with the number of items to be returned from the dictionary.
- Initialize an empty dictionary named “res”.
- Use a for loop with “test_dict.items()” to iterate over the key-value pairs of the dictionary.
- 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.
- If the length of “res” is equal to or greater than “K”, break out of the loop.
- Print the final dictionary named “res” limited to the first K items.
Python3
test_dict = {'gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'CS': 5}
print("The original dictionary : " + str(test_dict))
K = 3
res = {}
for key, value in test_dict.items():
if len(res) < K:
res[key] = value
else:
break
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
from itertools import islice
test_dict = {'gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'CS': 5}
print("The original dictionary : " + str(test_dict))
K = 3
res = dict(islice(test_dict.items(), K))
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.
Similar Reads
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()
6 min read
Python | Get the first key in dictionary
Many times, while working with Python, we can have a situation in which we are required to get the initial key of the dictionary. There can be many specific uses for it, either for checking the indexing or many more of these kinds. Let's discuss certain ways in which this task can be performed. Exam
3 min read
Python - Get next key in Dictionary
Sometimes, while working with Python dictionaries, we can have a problem in which we need to extract the next key in order of dictionary. This can have application as from Python 3.6 onwards the dictionaries are ordered. Lets discuss certain ways in which this task can be performed. Method #1 : Usin
3 min read
Python | Key index in Dictionary
The concept of dictionary is similar to that of map data structure in C++ language, but with the exception that keys in dictionary has nothing to do with its ordering, i.e it is not sorted unlike C++ in which the keys are sorted internally. This opens up the problem in which we might have to find th
3 min read
Python | Get items in sorted order from given dictionary
Given a dictionary, the task is to get all items from the dictionary in sorted order. Let's discuss different ways we can do this task. Method #1: Using sorted() C/C++ Code # Python code to demonstrate # to get sorted items from dictionary # initialising _dictionary ini_dict = {'a': 'akshat', 'b': '
3 min read
Python | Get total keys in dictionary
Sometimes, while working with Python dictionaries, one can come in a problem in which one needs to get the exact number of keys that are present in whole of dictionaries including ones that are nested. Let's discuss certain ways in which this task can be performed. Method #1 : Using recursion + item
4 min read
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
6 min read
Python - Extracting Kth Key in Dictionary
Many times, while working with Python, we can have a situation in which we require to get the Kth key of dictionary. There can be many specific uses of it, either for checking the indexing and many more of these kind. This is useful for Python version 3.8 +, where key ordering are similar as inserti
4 min read
Iterating List of Python Dictionaries
Iteration of the list of dictionaries is a very common practice that every developer performs while encountering with dictionary data. In this article, we will explore how to iterate through a list of dictionaries. Iterating List Of Dictionaries in PythonBelow are some of the ways by which we can it
3 min read
Dictionary items in value range in Python
In this article, we will explore different methods to extract dictionary items within a specific value range. The simplest approach involves using a loop. Using LoopThe idea is to iterate through dictionary using loop (for loop) and check each value against the given range and storing matching items
2 min read
Python - Maximum of filtered Keys in dictionary
Sometimes while working with Python dictionaries, we might have a problem in which we require to just maximum the selective key values from the dictionary. This problem can occur in web development domain. Let’s discuss certain ways in which this problem can be solved. Method #1: Using list comprehe
6 min read
Add item after given Key in dictionary in Python
To add an item after a given key in a dictionary we need to carefully manage the order of the items. Since Python 3.7 dictionaries maintain the order in which items are inserted. Using LoopThe idea is to iterate over the dictionary and copy each key: value pair to a new dictionary. When target key i
1 min read
Get size of a Dictionary in Python
These routines can be particularly useful when serving JSON objects over APIs since they can be used to keep the length and size of JSON objects under control. Web servers have restrictions on the size of JSON objects served via APIs. Finding the Size of the Dictionary in Bytes The size of a Diction
2 min read
Python | Filter Tuple Dictionary Keys
Sometimes, while working with Python dictionaries, we can have it’s keys in form of tuples. A tuple can have many elements in it and sometimes, it can be essential to get them. If they are a part of a dictionary keys and we desire to get filtered tuple key elements, we need to perform certain functi
4 min read
Python - Print dictionary of list values
In this article, we will explore various ways on How to Print Dictionary in Python of list values. A dictionary of list values means a dictionary contains values as a list of dictionaries in Python. Example: {'key1': [{'key1': value,......,'key n': value}........{'key1': value,......,'key n': value}
4 min read
Python | Get all tuple keys from dictionary
Sometimes, while working with Python dictionaries, we can have it's keys in form of tuples. A tuple can have many elements in it and sometimes, it can be essential to get them. If they are a part of a dictionary keys and we desire to get all the tuple key elements, we need to perform certain functio
7 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
Python Remove Item from Dictionary by Key
A dictionary in Python is a mutable and dynamic data type that provides a flexible way to access and manipulate data. As distinct from a list or a tuple, where elements are accessed via indices, a dictionary leverages a unique key representing each item. In this article, we will see how to remove it
3 min read
How can to get list of values from dictionary in Python?
In this article, we will discuss how to get a list of values from a dictionary using Python. Get list of values from dictionary using values() function We can use a dictionary.values() along with the list() function to get the list. Here, the values() method is a dictionary method used to access the
3 min read