Python | Extract specific keys from dictionary
Last Updated :
27 Jul, 2023
We have a lot of variations and applications of dictionary containers in Python and sometimes, we wish to perform a filter of keys in a dictionary, i.e extracting just the keys which are present in the particular container. Let's discuss certain ways in which this can be performed.
Extract specific keys from dictionary using dictionary comprehension + items()
This problem can be performed by reconstruction using the keys extracted through the items function that wishes to be filtered and the dictionary function makes the desired dictionary.
Python3
# initializing dictionary
test_dict = {'nikhil': 1, "akash": 2, 'akshat': 3, 'manjeet': 4}
# printing original list
print("The original dictionary : " + str(test_dict))
# Using dictionary comprehension + items()
# Extracting specific keys from dictionary
res = {key: test_dict[key] for key in test_dict.keys()
& {'akshat', 'nikhil'}}
# print result
print("The filtered dictionary is : " + str(res))
Output :
The original dictionary : {'manjeet': 4, 'akshat': 3, 'akash': 2, 'nikhil': 1}
The filtered dictionary is : {'akshat': 3, 'nikhil': 1}
The time complexity of the given code is O(n), where n is the number of elements in the dictionary.
The space complexity of the given code is O(k), where k is the number of keys extracted from the dictionary.
Extract specific keys from the dictionary using dict()
The dict() function can be used to perform this task by converting the logic performed using list comprehension into a dictionary.
Python3
# initializing dictionary
test_dict = {'nikhil': 1, "akash": 2, 'akshat': 3, 'manjeet': 4}
# printing original list
print("The original dictionary : " + str(test_dict))
# Using dict()
# Extracting specific keys from dictionary
res = dict((k, test_dict[k]) for k in ['nikhil', 'akshat']
if k in test_dict)
# print result
print("The filtered dictionary is : " + str(res))
Output :
The original dictionary : {'manjeet': 4, 'akshat': 3, 'akash': 2, 'nikhil': 1}
The filtered dictionary is : {'akshat': 3, 'nikhil': 1}
Time complexity: O(n), where n is the number of key-value pairs in the dictionary.
Auxiliary space: O(n), to store the keys and values in dictionary.
Extract specific keys from dictionary using filter()
This method involves using the filter() function to filter the keys in the dictionary:
Python3
#initializing dictionary
test_dict = {'nikhil': 1, "akash": 2, 'akshat': 3, 'manjeet': 4}
#printing original list
print("The original dictionary : " + str(test_dict))
#Using filter()
#Extracting specific keys from dictionary
keys_to_extract = ['nikhil', 'akshat']
res = dict(filter(lambda item: item[0] in keys_to_extract, test_dict.items()))
#print result
print("The filtered dictionary is : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy
OutputThe original dictionary : {'nikhil': 1, 'akash': 2, 'akshat': 3, 'manjeet': 4}
The filtered dictionary is : {'nikhil': 1, 'akshat': 3}
Time complexity: O(n)
Auxiliary Space: O(n) for storing the result
Extract specific keys from dictionary Using a for loop and a conditional statement
Initialize the dictionary:
- Define the list of keys to be extracted.
- Initialize an empty dictionary to store the extracted keys and their values.
- Use a for loop and a conditional statement to check if each key in the dictionary is in the list of keys to be extracted. If it is, add the key-value pair to the extracted dictionary.
- Print the extracted dictionary.
Python3
# initializing dictionary
test_dict = {'nikhil': 1, "akash": 2, 'akshat': 3, 'manjeet': 4}
# printing original list
print("The original dictionary is:", test_dict)
# defining keys to extract
keys_to_extract = ['nikhil', 'akshat']
# initializing an empty dictionary for extracted keys
extracted_dict = {}
# extracting keys using a for loop and conditional statement
for key, value in test_dict.items():
if key in keys_to_extract:
extracted_dict[key] = value
# printing the extracted dictionary
print("The extracted dictionary is:", extracted_dict)
OutputThe original dictionary is: {'nikhil': 1, 'akash': 2, 'akshat': 3, 'manjeet': 4}
The extracted dictionary is: {'nikhil': 1, 'akshat': 3}
Time complexity: O(n), where n is the number of key-value pairs in the dictionary.
Auxiliary space: O(k), where k is the number of keys to be extracted
Similar Reads
Extract Subset of Key-Value Pairs from Python Dictionary
In this article, we will study different approaches by which we can Extract the Subset Of Key-Value Pairs From the Python Dictionary. When we work with Python dictionaries, it often involves extracting subsets of key-value pairs based on specific criteria. This can be useful for tasks such as filter
4 min read
Python - Extract Key's value from Mixed Dictionaries List
Given a list of dictionaries, with each dictionary having different keys, extract value of key K. Input : test_list = [{"Gfg" : 3, "b" : 7}, {"is" : 5, 'a' : 10}, {"Best" : 9, 'c' : 11}], K = 'b' Output : 7 Explanation : Value of b is 7. Input : test_list = [{"Gfg" : 3, "b" : 7}, {"is" : 5, 'a' : 10
7 min read
Python Remove Key from Dictionary if Exists
We are given a dictionary and a key and our task is to remove the key from the dictionary if it exists. For example, d = {"a": 10, "b": 20, "c": 30} and key to remove is "b" then output will be {"a": 10, "c": 30}.Using pop() pop() method allows us to remove a key from a dictionary while specifying a
2 min read
Iterate Through Specific Keys in a Dictionary in Python
Sometimes we need to iterate through only specific keys in a dictionary rather than going through all of them. We can use various methods to iterate through specific keys in a dictionary in Python.Using dict.get() MethodWhen we're not sure whether a key exists in the dictionary and don't want to rai
3 min read
Python | Extract filtered Dictionary Values
While working with Python dictionaries, there can be cases in which we are just concerned about getting the filtered values list and donât care about keys. This is yet another essential utility and solution to it should be known and discussed. Letâs perform this task through certain methods. Method
4 min read
Remove Spaces from Dictionary Keys - Python
Sometimes, the keys in a dictionary may contain spaces, which can create issues while accessing or processing the data. For example, consider the dictionary d = {'first name': 'Nikki', 'last name': 'Smith'}. We may want to remove spaces from the keys to standardize the dictionary, resulting in {'fir
3 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
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 | 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
Get all Tuple Keys from Dictionary - Python
In Python, dictionaries can have tuples as keys which is useful when we need to store grouped values as a single key. Suppose we have a dictionary where the keys are tuples and we need to extract all the individual elements from these tuple keys into a list. For example, consider the dictionary : d
3 min read