Open In App

Python Program to Remove Nth element from Kth key’s value from the dictionary

Last Updated : 17 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a dictionary with value lists, our task is to write a Python program to remove N element from Kth key’s values.

Examples:

Input : test_dict = {“gfg” : [9, 4, 5, 2, 3, 2], “is” : [1, 2, 3, 4, 3, 2], “best” : [2, 2, 2, 3, 4]}, K, N = “gfg”, 2
Output : {‘gfg’: [9, 4, 5, 3], ‘is’: [1, 2, 3, 4, 3, 2], ‘best’: [2, 2, 2, 3, 4]}
Explanation : 2 removed from “gfg” key’s value list.

Input : test_dict = {“gfg” : [9, 4, 5, 2, 3, 2], “is” : [1, 2, 3, 4, 3, 2], “best” : [2, 2, 2, 3, 4]}, K, N = “gfg”, 4
Output : {‘gfg’: [9, 5, 2, 3, 2], ‘is’: [1, 2, 3, 4, 3, 2], ‘best’: [2, 2, 2, 3, 4]}
Explanation : 4 removed from “gfg” key’s value list.

Method #1 : Using loop + conditional statements

In this, reassignment of all the key along with their values is done, when K key occurs, N’s occurrence from its value list is omitted.

Python3




# Python3 code to demonstrate working of
# Remove N from K key's value in dictionary values list
# Using loop + conditional statements
 
# initializing dictionary
test_dict = {"gfg" : [9, 4, 5, 2, 3, 2],
             "is" : [1, 2, 3, 4, 3, 2],
             "best" : [2, 2, 2, 3, 4]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing K, N
K, N = "gfg", 2
 
res = dict()
for key, val in test_dict.items():
     
    # reassigning omitting desired number
    res[key] = (val if key != K else [idx for idx in val if idx != N])
 
# printing result
print("The altered dictionary : " + str(res))


Output

The original dictionary is : {'gfg': [9, 4, 5, 2, 3, 2], 'is': [1, 2, 3, 4, 3, 2], 'best': [2, 2, 2, 3, 4]}
The altered dictionary : {'gfg': [9, 4, 5, 3], 'is': [1, 2, 3, 4, 3, 2], 'best': [2, 2, 2, 3, 4]}

Time Complexity: O(n^2), where n is the number of occurrences of the given value k in the list.
Auxiliary Space: O(1)

Method #2: Using dictionary comprehension

In this, we perform similar task to above method, difference being use of dictionary comprehension instead of looping through keys using conventional loop.

Python3




# Python3 code to demonstrate working of
# Remove N from K key's value in dictionary values list
# Using dictionary comprehension
 
# initializing dictionary
test_dict = {"gfg" : [9, 4, 5, 2, 3, 2],
             "is" : [1, 2, 3, 4, 3, 2],
             "best" : [2, 2, 2, 3, 4]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing K, N
K, N = "gfg", 2
 
# dictionary comprehension used for shorthand
res = {key : (val if key != K else [idx for idx in val if idx != N]) for key, val in test_dict.items()}
 
# printing result
print("The altered dictionary : " + str(res))


Output

The original dictionary is : {'gfg': [9, 4, 5, 2, 3, 2], 'is': [1, 2, 3, 4, 3, 2], 'best': [2, 2, 2, 3, 4]}
The altered dictionary : {'gfg': [9, 4, 5, 3], 'is': [1, 2, 3, 4, 3, 2], 'best': [2, 2, 2, 3, 4]}

The time complexity of this program is O(n*m), where n is the number of key-value pairs in the dictionary and m is the length of the longest list in the values. 

The auxiliary space required is also O(n*m), since we are creating a new dictionary with potentially the same number of key-value pairs as the original dictionary, and each value may have a list with the same number of elements as the corresponding value in the original dictionary.

Method #3: Using index()+pop()

The function remove_element takes three parameters: a dictionary, a key, and a value k. It removes all occurrences of k from the list of values associated with the given key in the dictionary.

Step-by-step approach:

  • First, the function gets the list of values associated with the given key using dictionary[key].
  • Then, it counts the number of occurrences of the given value k in the list using value_list.count(k).
  • Next, it loops through the range of the count of the given value k.
  • In each iteration, it finds the index of the given value k using value_list.index(k), removes it from the list using value_list.pop(s).
  • Finally, it returns the modified dictionary.

Python3




def remove_element(dictionary, key, k):
    # get the value list for the given key
    value_list = dictionary[key]
    # remove the element at index (n-1) from the value list
    x=value_list.count(k)#find the count of k
    for i in range(x):#range of x
      s=value_list.index(k)# find index of k
      value_list.pop(s)#remove k from that dictionary
    return dictionary
test_dict = {"gfg": [9, 4, 5, 2, 3, 2], "is": [1, 2, 3, 4, 3, 2], "best": [2, 2, 2, 3, 4]}
key = "gfg"
k = 2
result = remove_element(test_dict, key, k)
print(result)


Output

{'gfg': [9, 4, 5, 3], 'is': [1, 2, 3, 4, 3, 2], 'best': [2, 2, 2, 3, 4]}

Time Complexity: O(n^2), where n is the number of occurrences of the given value k in the list. This is because for each occurrence of k, the function has to search for its index using value_list.index(k), which has a time complexity of O(n).
Auxiliary Space: O(1) because it does not use any additional data structure that grows with the input size

Method 4:  using the map() function along with a lambda function

Step-by-step approach:

  • Initialize the given dictionary.
  • Print the original dictionary.
  • Initialize the values of the given key K and the element N to remove from its value list.
  • Initialize an empty dictionary to store the altered values.
  • Loop through the items of the original dictionary.
  • For each item, check if the key matches the given key K.
  • If the key matches K, then use a lambda function along with filter() to remove the element N from the list value of the key. Store the new list value in the altered dictionary.
  • If the key does not match K, then simply store the existing list value in the altered dictionary.
  • After looping through all the items, print the altered dictionary.

Python3




# Python3 code to demonstrate working of
# Remove N from K key's value in dictionary values list
# Using map() + lambda
 
# initializing dictionary
test_dict = {"gfg" : [9, 4, 5, 2, 3, 2],
             "is" : [1, 2, 3, 4, 3, 2],
             "best" : [2, 2, 2, 3, 4]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing K, N
K, N = "gfg", 2
 
res = dict()
for key, val in test_dict.items():
     
    # reassigning omitting desired number using map() and lambda
    res[key] = list(map(lambda x: x if key != K else list(filter(lambda y: y != N, val)), val))
 
# printing result
print("The altered dictionary : " + str(res))


Output

The original dictionary is : {'gfg': [9, 4, 5, 2, 3, 2], 'is': [1, 2, 3, 4, 3, 2], 'best': [2, 2, 2, 3, 4]}
The altered dictionary : {'gfg': [[9, 4, 5, 3], [9, 4, 5, 3], [9, 4, 5, 3], [9, 4, 5, 3], [9, 4, 5, 3], [9, 4, 5, 3]], 'is': [1, 2, 3, 4, 3, 2], 'best': [2, 2, 2, 3, 4]}

Time complexity: O(NM), where N is the number of keys in the dictionary and M is the maximum length of the list values in the dictionary.
Auxiliary space: O(NM), as we are creating a new dictionary with the same number of keys and list values.

Method #5: Using list comprehension

Algorithm:

  • Initialize an empty dictionary called “res”.
  • Loop through each key-value pair in the original dictionary “test_dict”.
  • For each key-value pair, use list comprehension to create a new list that is the original list with the desired number “N” removed from the value list associated with key “K”.
  • Store the new list as the value in the dictionary “res” with the corresponding key.
  • Return the altered dictionary “res”.

Python3




# Python3 code to demonstrate working of
# Remove N from K key's value in dictionary values list
# Using list comprehension
 
# initializing dictionary
test_dict = {"gfg": [9, 4, 5, 2, 3, 2],
             "is": [1, 2, 3, 4, 3, 2],
             "best": [2, 2, 2, 3, 4]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing K, N
K, N = "gfg", 2
 
# using list comprehension to create new list
res = {key: [val_elem for val_elem in val if (key != K) or (
    val_elem != N)] for key, val in test_dict.items()}
 
# printing result
print("The altered dictionary : " + str(res))


Output

The original dictionary is : {'gfg': [9, 4, 5, 2, 3, 2], 'is': [1, 2, 3, 4, 3, 2], 'best': [2, 2, 2, 3, 4]}
The altered dictionary : {'gfg': [9, 4, 5, 3], 'is': [1, 2, 3, 4, 3, 2], 'best': [2, 2, 2, 3, 4]}

Time complexity: O(n * m), where n is the number of key-value pairs in the dictionary and m is the length of the longest value list in the dictionary.

Auxiliary space: O(n * m), where n is the number of key-value pairs in the dictionary and m is the length of the longest value list in the dictionary.

Method#6: Using Recursive method.

Algorithm:

  1. Define a function remove_n_from_k that takes in three arguments: test_dict, K, and N.
  2. Check if the key K is present in the dictionary test_dict.
  3. If the key K is present, update its value by removing all occurrences of N from its value list using a list comprehension.
  4. Return the updated dictionary.

Python3




def remove_n_from_k(test_dict, K, N):
    if K in test_dict:
        test_dict[K] = [x for x in test_dict[K] if x != N]
    return test_dict
 
test_dict = {"gfg" : [9, 4, 5, 2, 3, 2],
             "is" : [1, 2, 3, 4, 3, 2],
             "best" : [2, 2, 2, 3, 4]}
K = "gfg"
N = 2
 
print("The original dictionary is : " + str(test_dict))
res = remove_n_from_k(test_dict, K, N)
print("The altered dictionary : " + str(res))


Output

The original dictionary is : {'gfg': [9, 4, 5, 2, 3, 2], 'is': [1, 2, 3, 4, 3, 2], 'best': [2, 2, 2, 3, 4]}
The altered dictionary : {'gfg': [9, 4, 5, 3], 'is': [1, 2, 3, 4, 3, 2], 'best': [2, 2, 2, 3, 4]}

The time complexity of this algorithm is O(n), where n is the length of the value list associated with key K. This is because we need to iterate over the entire list to remove all occurrences of N.

The auxiliary space of this algorithm is O(n), where n is the length of the value list associated with key K. This is because we need to create a new list to store the updated values.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads