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
test_dict = { 'gfg' : 1 , 'is' : 2 , 'best' : 3 , 'for' : 4 , 'CS' : 5 }
print ( "The original dictionary : " + str (test_dict))
key_list = [ 'gfg' , 'best' , 'CS' ]
res = [test_dict.get(key) for key in key_list]
print ( "The values of Selective keys : " + str (res))
|
Output
The 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
from operator import itemgetter
test_dict = { 'gfg' : 1 , 'is' : 2 , 'best' : 3 , 'for' : 4 , 'CS' : 5 }
print ( "The original dictionary : " + str (test_dict))
key_list = [ 'gfg' , 'best' , 'CS' ]
res = list (itemgetter( * key_list)(test_dict))
print ( "The values of Selective keys : " + str (res))
|
Output
The 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
test_dict = { 'gfg' : 1 , 'is' : 2 , 'best' : 3 , 'for' : 4 , 'CS' : 5 }
print ( "The original dictionary : " + str (test_dict))
key_list = [ 'gfg' , 'best' , 'CS' ]
res = []
for i in key_list:
res.append(test_dict[i])
print ( "The values of Selective keys : " + str (res))
|
Output
The 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
test_dict = { 'gfg' : 1 , 'is' : 2 , 'best' : 3 , 'for' : 4 , 'CS' : 5 }
print ( "The original dictionary : " + str (test_dict))
key_list = [ 'gfg' , 'best' , 'CS' ]
res = {key: test_dict[key] for key in key_list}.values()
print ( "The values of Selective keys : " + str (res))
|
Output
The 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
test_dict = { 'gfg' : 1 , 'is' : 2 , 'best' : 3 , 'for' : 4 , 'CS' : 5 }
print ( "The original dictionary : " + str (test_dict))
key_list = [ 'gfg' , 'best' , 'CS' ]
res = list ( map (test_dict.get, key_list))
print ( "The values of Selective keys : " + str (res))
|
Output
The 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
import operator
test_dict = { 'gfg' : 1 , 'is' : 2 , 'best' : 3 , 'for' : 4 , 'CS' : 5 }
print ( "The original dictionary : " + str (test_dict))
key_list = [ 'gfg' , 'best' , 'CS' ]
res = list ( map (operator.itemgetter( * key_list), [test_dict]))
print ( "The values of Selective keys : " + str (res))
|
Output
The 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))
|
Output
The 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 - Smallest K values in Dictionary
Many times while working with Python dictionary, we can have a particular problem to find the K minima of values in numerous keys. This problem is quite common while working with web development domain. Letâs discuss several ways in which this task can be performed. Smallest K values in Dictionary u
4 min read
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 value
4 min read
Set from Dictionary Values - Python
The task is to extract unique values from a dictionary and convert them into a set. In Python, sets are unordered collections that automatically eliminate duplicates. The goal is to extract all the values from the dictionary and store them in a set. For example, given a dictionary like d = {'A': 4,
3 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 - Resize Keys in dictionary
Given Dictionary, resize keys to K by getting starting k elements from keys. Input : test_dict = {"geeksforgeeks" :3, "best" :3, "coding" :4, "practice" :3}, K = 3 Output : {'gee': 3, 'bes': 3, 'cod': 4, 'pra': 3} Explanation : Keys resized to have 3 elements. Input : test_dict = {"geeksforgeeks" :3
3 min read
Python Dictionary Add Value to Existing Key
The task of adding a value to an existing key in a Python dictionary involves modifying the value associated with a key that is already present. Unlike adding new key-value pairs, this operation focuses on updating the value of an existing key, allowing us to increment, concatenate or otherwise adju
2 min read
Python - Sort Dictionary by Values and Keys
Given a dictionary, sort according to descended values, if similar values, then by keys lexicographically. Input : test_dict = {"gfg" : 1, "is" : 1, "best" : 1, "for" : 1, "geeks" : 1} Output : {"best" : 1, "is" : 1, "for" : 1, "geeks" : 1, "gfg" : 1} Explanation : All values are equal, hence lexico
3 min read
Python - Dictionary items in value range
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 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