Open In App

Python – Remove digits from Dictionary String Values List

Improve
Improve
Like Article
Like
Save
Share
Report

Given list of dictionaries with string list values, remove all the numerics from all strings.

Input: test_dict = {'Gfg' : ["G4G is Best 4", "4 ALL geeks"], 
                    'best' : ["Gfg Heaven", "for 7 CS"]} 
                    
Output: {'Gfg': ['GG is Best ', ' ALL geeks'], 
                'best': ['Gfg Heaven', 'for CS']} 

Explanation: All the numeric strings are removed. 

Input: test_dict = {'Gfg' : ["G4G is Best 4", "4 ALL geeks"]} 

Output: {'Gfg': ['GG is Best ', ' ALL geeks']} 

Explanation: All the numeric strings are removed.

Method 1: Using regex + dictionary comprehension

This problem can be solved using a combination of both functionalities. In this, we applthe y regex to replace each digit with an empty string and compile the result using dictionary comprehension.

Python3




# Python3 code to demonstrate working of
# Remove digits from Dictionary String Values List
# Using loop + regex() + dictionary comprehension
import re
 
# initializing dictionary
test_dict = {'Gfg': ["G4G is Best 4", "4 ALL geeks"],
             'is': ["5 6 Good"],
             'best': ["Gfg Heaven", "for 7 CS"]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# using dictionary comprehension to go through all keys
res = {key: [re.sub('\d', '', ele) for ele in val]
       for key, val in test_dict.items()}
 
# printing result
print("The filtered dictionary : " + str(res))


Output

The original dictionary is : {'Gfg': ['G4G is Best 4', '4 ALL geeks'], 'is': ['5 6 Good'], 'best': ['Gfg Heaven', 'for 7 CS']}
The filtered dictionary : {'Gfg': ['GG is Best ', ' ALL geeks'], 'is': ['  Good'], 'best': ['Gfg Heaven', 'for  CS']}

Time complexity: O(nm), where n is the number of keys in the dictionary and m is the maximum length of the list values.
Auxiliary space: O(nm), as we are creating a new dictionary with the same number of keys and values as the original one, and each list value can have the same length as the original one. Additionally, we are creating a new list for each value in the dictionary comprehension.

Method 2: Without using regex

Step-by-step approach:

  • Create an empty dictionary res.
  • Iterate over the keys of the dictionary test_dict using a for loop. For each key i, initialize an empty list v.
  • Iterate over the string values of the key i using another for loop. For each string j, apply the function fun() to remove the digits from it and append the result to the list v.
  • Assign the list v to the key i in the dictionary res.
  • After the completion of the for loop, the dictionary res will contain the filtered dictionary.
  • Print the filtered dictionary using the print() function.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# Remove digits from Dictionary String Values List
 
 
def fun(s):
    x = ""
    for i in s:
        if not i.isdigit():
            x += i
    return x
 
 
# initializing dictionary
test_dict = {'Gfg': ["G4G is Best 4", "4 ALL geeks"],
             'is': ["5 6 Good"],
             'best': ["Gfg Heaven", "for 7 CS"]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# using dictionary comprehension to go through all keys
res = dict()
for i in test_dict:
    v = []
    for j in test_dict[i]:
        v.append(fun(j))
    res[i] = v
 
# printing result
print("The filtered dictionary : " + str(res))


Output

The original dictionary is : {'Gfg': ['G4G is Best 4', '4 ALL geeks'], 'is': ['5 6 Good'], 'best': ['Gfg Heaven', 'for 7 CS']}
The filtered dictionary : {'Gfg': ['GG is Best ', ' ALL geeks'], 'is': ['  Good'], 'best': ['Gfg Heaven', 'for  CS']}

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

Method 3: Using replace() method

Python3




# Python3 code to demonstrate working of
# Remove digits from Dictionary String Values List
 
 
def fun(s):
    digits = "0123456789"
    for i in digits:
        s = s.replace(i, "")
    return s
 
 
# initializing dictionary
test_dict = {'Gfg': ["G4G is Best 4", "4 ALL geeks"],
             'is': ["5 6 Good"],
             'best': ["Gfg Heaven", "for 7 CS"]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# using dictionary comprehension to go through all keys
res = dict()
for i in test_dict:
    v = []
    for j in test_dict[i]:
        v.append(fun(j))
    res[i] = v
 
# printing result
print("The filtered dictionary : " + str(res))


Output

The original dictionary is : {'Gfg': ['G4G is Best 4', '4 ALL geeks'], 'is': ['5 6 Good'], 'best': ['Gfg Heaven', 'for 7 CS']}
The filtered dictionary : {'Gfg': ['GG is Best ', ' ALL geeks'], 'is': ['  Good'], 'best': ['Gfg Heaven', 'for  CS']}

Time Complexity: O(nmk), where n is the number of keys in the dictionary, m is the average number of string values for each key, and k is the average length of each string value.
Auxiliary Space: O(nmk), as we are creating a new list of filtered string values for each key in the dictionary.

Method 4: Using filtering

The code filters out the numeric characters and spaces from each string in the list and keeps only alphabetic characters. The filter function is used to achieve this. The filter function takes a function and an iterable as input, and returns an iterable containing only the items for which the function returns True. In this case, the function being passed to filter returns True for alphabetic characters and spaces and False for numeric characters. The filtered strings are then joined together to form the final result.

Python3




def remove_numerics(test_dict):
    result = {}
    for key, value in test_dict.items():
        result[key] = [
            ''.join(filter(lambda x: x.isalpha() or x.isspace(), item)) for item in value]
    return result
 
 
if __name__ == '__main__':
    test_dict = {'Gfg': ["G4G is Best 4", "4 ALL geeks"],'is': ["5 6 Good"],'best': ["Gfg Heaven", "for 7 CS"]}
    # printing original dictionary
    print("The original dictionary is : " + str(test_dict))
     
    result = remove_numerics(test_dict)
    print("The filtered dictionary : ", result)


Output

The original dictionary is : {'Gfg': ['G4G is Best 4', '4 ALL geeks'], 'is': ['5 6 Good'], 'best': ['Gfg Heaven', 'for 7 CS']}
The filtered dictionary :  {'Gfg': ['GG is Best ', ' ALL geeks'], 'is': ['  Good'], 'best': ['Gfg Heaven', 'for  CS']}

Time complexity: O(n * m) where n is the number of keys in the dictionary and m is the maximum length of strings in the values of the dictionary.
Auxiliary Space: O(n * m) as we are storing the result of filtering each string in memory.

Method 5: Using for loop 

Step-by-step approach:

  • Import the “re” module to use regular expressions.
  • Create an empty dictionary to store the filtered results.
  • Iterate over the original dictionary using a for loop.
    • For each key-value pair in the original dictionary, create an empty list in the result dictionary.
    • Iterate over each string element in the list of values associated with the current key.
      • Apply the regular expression to remove any digits from the string.
      • Append the filtered string to the list associated with the current key in the result dictionary.
  • Print the filtered dictionary

Below is the implementation of the above approach:

Python3




import re
 
# initializing dictionary
test_dict = {'Gfg': ["G4G is Best 4", "4 ALL geeks"],
             'is': ["5 6 Good"],
             'best': ["Gfg Heaven", "for 7 CS"]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
res = {}
for key, val in test_dict.items():
    res[key] = []
    for ele in val:
        res[key].append(re.sub('\d', '', ele))
 
# printing result
print("The filtered dictionary : " + str(res))


Output

The original dictionary is : {'Gfg': ['G4G is Best 4', '4 ALL geeks'], 'is': ['5 6 Good'], 'best': ['Gfg Heaven', 'for 7 CS']}
The filtered dictionary : {'Gfg': ['GG is Best ', ' ALL geeks'], 'is': ['  Good'], 'best': ['Gfg Heaven', 'for  CS']}

Time complexity: O(n), where n is the number of elements in the original dictionary, because we are iterating over all the elements in the dictionary.
Auxiliary space: O(n), because we are creating a new dictionary to store the results of the filtering operation. 

Method 6: Using map() method

Use the map() method to iterate through each value in the dictionary and apply the re.sub() method to remove all digits from the string.

step by step approach of the program:

Step 1: Import the re module for regular expressions.

Step 2: Initialize a dictionary called “test_dict” that contains key-value pairs. Each key is a string and each value is a list of strings.

Step 3: Print the original dictionary using the print() function.

Step 4: Use the map() function with a lambda function to remove all digits from each string in the value lists of the dictionary.

Step 5: Use the re.sub() function to replace all digits in a string with an empty string (”).

Step 6: Store the filtered values in a new dictionary called “res” with the same keys as the original dictionary.

Step 7: Print the filtered dictionary using the print() function.

Python3




import re
 
# initializing dictionary
test_dict = {'Gfg': ["G4G is Best 4", "4 ALL geeks"],
             'is': ["5 6 Good"],
             'best': ["Gfg Heaven", "for 7 CS"]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# using map() method to remove digits from string
res = {key: list(map(lambda x: re.sub('\d', '', x), val)) for key, val in test_dict.items()}
 
# printing result
print("The filtered dictionary : " + str(res))


Output

The original dictionary is : {'Gfg': ['G4G is Best 4', '4 ALL geeks'], 'is': ['5 6 Good'], 'best': ['Gfg Heaven', 'for 7 CS']}
The filtered dictionary : {'Gfg': ['GG is Best ', ' ALL geeks'], 'is': ['  Good'], 'best': ['Gfg Heaven', 'for  CS']}

Time complexity: O(nmk), where n is the number of keys in the dictionary, m is the maximum number of strings in the dictionary values list, and k is the maximum length of a string in the dictionary values list.
Auxiliary space: O(nmk), as the resulting filtered dictionary has the same size as the original dictionary, with each string having at most the same length as the original string. 

Method 7: Using list comprehension with conditional statement

Step-by-step approach:

  1. Initialize an empty dictionary named result_dict.
  2. Iterate through each key-value pair of test_dict using a for loop.
  3. For each value in the current key-value pair, create a list comprehension that removes digits from the string if a digit is present. If no digit is present, add the original string to the list comprehension.
  4. Add the key-value pair to the result_dict where the key is the current key in the iteration and the value is the list comprehension from step 3.
  5. Print the result_dict.

Below is the implementation of the above approach:

Python3




# initializing dictionary
test_dict = {'Gfg': ["G4G is Best 4", "4 ALL geeks"],
             'is': ["5 6 Good"],
             'best': ["Gfg Heaven", "for 7 CS"]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# using list comprehension with conditional statement to remove digits from string
result_dict = {}
for key, val in test_dict.items():
    result_dict[key] = [s.translate(str.maketrans('', '', '0123456789')) if any(c.isdigit() for c in s) else s for s in val]
 
# printing result
print("The filtered dictionary : " + str(result_dict))


Output

The original dictionary is : {'Gfg': ['G4G is Best 4', '4 ALL geeks'], 'is': ['5 6 Good'], 'best': ['Gfg Heaven', 'for 7 CS']}
The filtered dictionary : {'Gfg': ['GG is Best ', ' ALL geeks'], 'is': ['  Good'], 'best': ['Gfg Heaven', 'for  CS']}

Time complexity: O(nm) where n is the number of keys in test_dict and m is the length of the longest list of strings associated with a key.
Auxiliary space: O(nm) since the result dictionary contains n keys and each key can have a list of strings with up to m elements.



Last Updated : 10 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads