Python | Selective key values in dictionary
Last Updated :
27 Apr, 2023
Sometimes while working with Python dictionaries, we might have a problem in which we require to just get 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 comprehension + get() The combination of the above functions can be used to perform this particular task. In this, we access the values using the get method and traverse the dictionary using list comprehension.
Python3
# Python3 code to demonstrate working of
# Selective key values in dictionary
# Using list comprehension + get()
# Initialize dictionary
test_dict = {'gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'CS': 5}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# Initialize key list
key_list = ['gfg', 'best', 'CS']
# Using list comprehension + get()
# Selective key values in dictionary
res = [test_dict.get(key) for key in key_list]
# printing result
print("The values of Selective keys : " + str(res))
OutputThe original dictionary : {'gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'CS': 5}
The values of Selective keys : [1, 3, 5]
The time complexity of this implementation is O(n), where n is the number of keys in the key_list.
The auxiliary space complexity of this implementation is also O(n), since we are creating a new list res with one element for each key in the key_list.
Method #2: Using itemgetter() This single function can be used to perform this particular task. It is built in to perform this specific task. It takes chain of keys and returns the corresponding values as a tuple which can be type casted.
Python3
# Python3 code to demonstrate working of
# Selective key values in dictionary
# Using itemgetter()
from operator import itemgetter
# Initialize dictionary
test_dict = {'gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'CS': 5}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# Initialize key list
key_list = ['gfg', 'best', 'CS']
# Using itemgetter()
# Selective key values in dictionary
res = list(itemgetter(*key_list)(test_dict))
# printing result
print("The values of Selective keys : " + str(res))
OutputThe original dictionary : {'gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'CS': 5}
The values of Selective keys : [1, 3, 5]
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 #3 : Using for loop
Python3
# Python3 code to demonstrate working of
# Selective key values in dictionary
# Initialize dictionary
test_dict = {'gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'CS': 5}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# Initialize key list
key_list = ['gfg', 'best', 'CS']
# Selective key values in dictionary
res = []
for i in key_list:
res.append(test_dict[i])
# printing result
print("The values of Selective keys : " + str(res))
OutputThe original dictionary : {'gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'CS': 5}
The values of Selective keys : [1, 3, 5]
Time complexity: O(k), where k is the number of selected keys.
Auxiliary space: O(k), where k is the number of selected keys.
Method #4 : Using dictionary comprehension
Python3
# Python3 code to demonstrate working of
# Selective key values in dictionary
# Initialize dictionary
test_dict = {'gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'CS': 5}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# Initialize key list
key_list = ['gfg', 'best', 'CS']
# Using dictionary comprehension
# Selective key values in dictionary
res = {key: test_dict[key] for key in key_list}.values()
# printing result
print("The values of Selective keys : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy
OutputThe original dictionary : {'gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'CS': 5}
The values of Selective keys : dict_values([1, 3, 5])
Time Complexity: O(n)
Auxiliary Space: O(1)
Method #5: Using the map() function
The map() function takes two arguments - the function test_dict.get which retrieves the value for each key in the key_list, and the key_list itself. The map() function returns a map object, which is then converted to a list using the list() function.
Python3
# Python3 code to demonstrate working of
# Selective key values in dictionary
# Initialize dictionary
test_dict = {'gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'CS': 5}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# Initialize key list
key_list = ['gfg', 'best', 'CS']
# Using map() function
# Selective key values in dictionary
res = list(map(test_dict.get, key_list))
# printing result
print("The values of Selective keys : " + str(res))
OutputThe original dictionary : {'gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'CS': 5}
The values of Selective keys : [1, 3, 5]
Time complexity: O(n), where n is the length of the key_list.
Auxiliary space: O(n), where n is the length of the key_list.
Method 6: Using the operator module
This method uses the itemgetter function to get the values corresponding to the keys in key_list. The map function applies the itemgetter function to each key in key_list. The result is a list of values for the keys in key_list.
Python3
# Python3 code to demonstrate working of
# Selective key values in dictionary
# Using the operator module
# Import the operator module
import operator
# Initialize dictionary
test_dict = {'gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'CS': 5}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# Initialize key list
key_list = ['gfg', 'best', 'CS']
# Selective key values in dictionary using the operator module
res = list(map(operator.itemgetter(*key_list), [test_dict]))
# printing result
print("The values of Selective keys : " + str(res))
OutputThe original dictionary : {'gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'CS': 5}
The values of Selective keys : [(1, 3, 5)]
Time complexity: O(k), where k is the length of the key_list.
Auxiliary space: O(k), because we are creating a new list res of length k to store the values corresponding to the keys in key_list.
Method#7: Using Recursive method.
Algorithm:
1. Base Case: If the input key list is empty, return an empty list.
2. Recursive Case: Take the first element of the key list and call it `head`. Take the rest of the key list and call it `tail`.
3. Recursively call `selective_values` on the `tail` of the key list.
4. If `head` is a key in the input dictionary, append its value to the result list. Otherwise, return the result list without appending anything.
Python3
def selective_values(test_dict, key_list):
if not key_list:
return []
head = key_list[0]
tail = key_list[1:]
res = selective_values(test_dict, tail)
return [test_dict[head]] + res if head in test_dict else res
test_dict = {'gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'CS': 5}
key_list = ['gfg', 'best', 'CS']
res = selective_values(test_dict, key_list)
print("The values of Selective keys : " + str(res))
OutputThe values of Selective keys : [1, 3, 5]
Time Complexity: O(n) - The recursive function is called n times, once for each key in the input key list. Dictionary lookup has an average time complexity of O(1), so the overall time complexity is dominated by the recursive calls, which gives us O(n).
Auxiliary Space: O(n) - The recursive function creates a new list for each recursive call, so the space complexity is proportional to the size of the input key list. In the worst case, where all keys are present in the dictionary, the size of the output list is the same as the size of the input key list, so the space complexity is O(n).
Similar Reads
Python - Unique Values of Key in Dictionary We are given a list of dictionaries and our task is to extract all the unique values associated with a given key. For example, consider: data = [ {"name": "Aryan", "age": 25}, {"name": "Harsh", "age": 30}, {"name": "Kunal", "age": 22}, {"name": "Aryan", "age": 27}]key = "name"Then, the unique values
4 min read
Filter Dictionary Key based on the Values in Selective List - Python We are given a dictionary where each key is associated with a value and our task is to filter the dictionary based on a selective list of values. We want to retain only those key-value pairs where the value is present in the list. For example, we have the following dictionary and list: d = {'apple':
3 min read
Python Update Dictionary Value by Key A Dictionary in Python is an unordered collection of key-value pairs. Each key must be unique, and you can use various data types for both keys and values. Dictionaries are enclosed in curly braces {}, and the key-value pairs are separated by colons. Python dictionaries are mutable, meaning you can
3 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 Dictionary if Given Key's Value is N We are given a dictionary we need to remove key if the given value of key is N. For example, we are given a dictionary d = {'a': 1, 'b': 2, 'c': 3} we need to remove the key if the value is N so that the output becomes {'a': 1, 'c': 3}. We can use methods like del, pop and various other methods like
2 min read