Monday, November 18, 2024
Google search engine
HomeLanguagesPython | Filter dictionary key based on the values in selective list

Python | Filter dictionary key based on the values in selective list

In Python, sometimes we require to get only some of the dictionary keys and not all. This problem is quite common in web development we require to get only the selective dictionary keys from some given list. Let’s discuss certain ways in which this problem can be solved. 

Method #1: Using list comprehension 

The list comprehension can be used to solve this particular problem. This is just the shorthand way of performing it instead of writing a loop. 

Python3




# Python3 code to demonstrate
# getting selective dictionary keys
# using list comprehension
 
# initializing dictionary
test_dict = {"Akash" : 1, "Akshat" : 2, "Nikhil" : 3, "Manjeet" : 4}
 
# initializing selective list keys
select_list = ['Manjeet', 'Nikhil']
 
# printing original dictionary
print ("The original dictionary is : " + str(test_dict))
 
# printing selective list
print ("The selective list is : " + str(select_list))
 
# using list comprehension
# getting selective dictionary keys
res = [test_dict[i] for i in select_list if i in test_dict]
 
# printing result
print ("The selected values from list keys is : " + str(res))


Output

The original dictionary is : {'Akash': 1, 'Akshat': 2, 'Nikhil': 3, 'Manjeet': 4}
The selective list is : ['Manjeet', 'Nikhil']
The selected values from list keys is : [4, 3]

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #2: Using set.intersection() This is the most elegant method in which this task can be performed. The intersection property of sets can give the common keys that can be extracted and then values can be computed. 

Python3




# Python3 code to demonstrate
# getting selective dictionary keys
# using set.intersection()
 
# initializing dictionary
test_dict = {"Akash" : 1, "Akshat" : 2, "Nikhil" : 3, "Manjeet" : 4}
 
# initializing selective list keys
select_list = ['Manjeet', 'Nikhil']
 
# printing original dictionary
print ("The original dictionary is : " + str(test_dict))
 
# printing selective list
print ("The selective list is : " + str(select_list))
 
# using set.intersection()
# getting selective dictionary keys
temp = list(set(select_list).intersection(test_dict))
res = [test_dict[i] for i in temp]
 
# printing result
print ("The selected values from list keys is : " + str(res))


Output

The original dictionary is : {'Akash': 1, 'Akshat': 2, 'Nikhil': 3, 'Manjeet': 4}
The selective list is : ['Manjeet', 'Nikhil']
The selected values from list keys is : [3, 4]

Time complexity: O(n), where n is the length of the longest input, i.e., the length of the list select_list or the number of keys in the dictionary test_dict, whichever is larger. This is because the program iterates through the list once to create a set, iterates through the dictionary once to check for intersection, and iterates through the resulting keys once to retrieve the values.
Auxiliary space: O(m), where m is the number of keys in the resulting dictionary. This is because the program creates a set and a list of length at most m to store the intersection of keys and the corresponding values.

Method 3: Using simple for loop:

  • Initialize a dictionary called test_dict with some key-value pairs.
  • Initialize a list called select_list with some keys from the dictionary.
  • Print the original dictionary and the selective list.
  • Create an empty list called res to store the selected values from the dictionary.
  • Loop through each key in the select_list.
    • Check if the key exists in the test_dict dictionary using an if statement.
      • If the key exists, add the corresponding value to the res list using the append() method.
    • After all keys have been checked, print the res list, which contains the selected values from the dictionary.

Python3




# initializing dictionary
test_dict = {"Akash": 1, "Akshat": 2, "Nikhil": 3, "Manjeet": 4}
 
# initializing selective list keys
select_list = ['Manjeet', 'Nikhil']
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# printing selective list
print("The selective list is : " + str(select_list))
 
# using for loop to iterate over selective list and get
# corresponding values from dictionary
res = []
for key in select_list:
    # check if key is in dictionary
    if key in test_dict:
        # add corresponding value to result list
        res.append(test_dict[key])
 
# printing result
print("The selected values from list keys is : " + str(res))


Output

The original dictionary is : {'Akash': 1, 'Akshat': 2, 'Nikhil': 3, 'Manjeet': 4}
The selective list is : ['Manjeet', 'Nikhil']
The selected values from list keys is : [4, 3]

Time Complexity: O(n)
Auxiliary Space: O(n)

Method 4: Using filter() function

 The filter() function checks if each key in the selective list is present in the dictionary using the __contains__() method of the dictionary. The resulting filtered list of keys is then passed to the map() function along with the get() method of the dictionary. The map() function returns the values corresponding to each key in the filtered list.

Python3




# initializing dictionary
test_dict = {"Akash" : 1, "Akshat" : 2, "Nikhil" : 3, "Manjeet" : 4}
 
# initializing selective list keys
select_list = ['Manjeet', 'Nikhil']
 
# using filter() and map() functions
# getting selective dictionary keys
res = list(map(test_dict.get, filter(test_dict.__contains__, select_list)))
 
# printing result
print ("The selected values from list keys is : " + str(res))


Output

The selected values from list keys is : [4, 3]

The time complexity of this approach is O(n), where n is the length of the selective list.
The auxiliary space complexity of this approach is O(m), where m is the number of keys in the selective list that are also present in the dictionary.

Method#5: Using the Recursive method.

Step-by-step approach:

  • Initialize the dictionary and selective list.
  • Define a recursive function that takes the dictionary and the list of keys as parameters.
  • If the list of keys is empty, return an empty list.
  • Get the first key from the list.
  • Check if the key is in the dictionary.
  • If the key is in the dictionary, add its value to the result list.
  • Recursively call the function with the remaining keys in the list.
  • Concatenate the result of step 6 with the result of step 7.
  • Return the result list.

Below is the implementation of the above approach:

Python3




# defining the recursive function
def get_values_recursive(dictionary, keys):
    # base case: if the list of keys is empty
    if not keys:
        return []
     
    # get the first key from the list
    key = keys[0]
     
    # if the key is in the dictionary, add its value to the result list
    if key in dictionary:
        res = [dictionary[key]]
    else:
        res = []
     
    # recursively call the function with the remaining keys in the list
    res += get_values_recursive(dictionary, keys[1:])
     
    return res
 
 
# initializing dictionary
test_dict = {"Akash": 1, "Akshat": 2, "Nikhil": 3, "Manjeet": 4}
 
# initializing selective list keys
select_list = ['Manjeet', 'Nikhil']
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# printing selective list
print("The selective list is : " + str(select_list))
 
# calling the recursive function to get the values for the selected keys
res = get_values_recursive(test_dict, select_list)
 
# printing result
print("The selected values from list keys is : " + str(res))


Output

The original dictionary is : {'Akash': 1, 'Akshat': 2, 'Nikhil': 3, 'Manjeet': 4}
The selective list is : ['Manjeet', 'Nikhil']
The selected values from list keys is : [4, 3]

Time complexity: O(n), where n is the length of the selective list. 
Auxiliary Space: O(n), where n is the length of the selective list. 

Method #6: Using Dictionary Comprehension

Step-by-step approach:

  • Use dictionary comprehension to create a list named res which contains the values corresponding to the selected keys from the dictionary test_dict.
  • Check if each key in select_list is present in test_dict using the if statement in the dictionary comprehension.
  • Retrieve the value of each selected key using test_dict[key].
  • Store the values of the selected keys in a list named res.
  • Print the selected values from the list of keys.

Below is the implementation of the above approach:

Python3




# initializing dictionary
test_dict = {"Akash": 1, "Akshat": 2, "Nikhil": 3, "Manjeet": 4}
 
# initializing selective list keys
select_list = ['Manjeet', 'Nikhil']
 
# using dictionary comprehension to get values for selected keys
res = [test_dict[key] for key in select_list if key in test_dict]
 
# printing result
print("The selected values from list keys is : " + str(res))


Output

The selected values from list keys is : [4, 3]

Time complexity: O(n), where n is the number of keys in the dictionary. 
Auxiliary space: O(k), where k is the number of selected keys. 

Method #7: Using numpy:
 

 Algorithm:

  1. Initialize the input dictionary and the selective list of keys.
  2. Convert the dictionary to a numpy array using the list() and array() methods.
  3. Filter the numpy array to keep only the rows with keys in the selective list using the np.isin() method.
  4. Extract the values from the filtered numpy array using indexing and the map() function to convert the string values to integers.
  5. Print the resulting list of values.

Python3




import numpy as np
 
# initializing dictionary
test_dict = {"Akash": 1, "Akshat": 2, "Nikhil": 3, "Manjeet": 4}
 
# initializing selective list keys
select_list = ['Manjeet', 'Nikhil']
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# printing selective list
print("The selective list is : " + str(select_list))
 
# convert the dictionary to a numpy array
arr = np.array(list(test_dict.items()))
 
# filter the numpy array to keep only the selected keys
filtered_arr = arr[np.isin(arr[:, 0], select_list)]
 
# extract the values from the filtered array
res = list(map(int, filtered_arr[:, 1]))
 
# printing result
print("The selected values from list keys is : " + str(res))
#This code is contributed by Rayudu.


Output:

The original dictionary is : {‘Akash’: 1, ‘Akshat’: 2, ‘Nikhil’: 3, ‘Manjeet’: 4}
The selective list is : [‘Manjeet’, ‘Nikhil’]
The selected values from list keys is : [3, 4]

Time complexity: O(n), where n is the number of items in the dictionary.

Space complexity: O(n), where n is the number of items in the dictionary.

RELATED ARTICLES

Most Popular

Recent Comments