The Wayback Machine - https://web.archive.org/web/20240717054034/https://www.geeksforgeeks.org/python-remove-digits-from-dictionary-string-values-list/
Open In App

Python – Remove digits from Dictionary String Values List

Last Updated : 10 Apr, 2023
Improve
Suggest changes
Post a comment
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.



Similar Reads

Python - Remove duplicate values across Dictionary Values
Sometimes, while working with Python dictionaries, we can have a problem in which we need to remove all the duplicate values across all the dictionary value lists. This problem can have applications in data domains and web development domains. Let's discuss certain ways in which this task can be performed. Input: test_dict = {'Manjeet': [1], 'Akash
8 min read
Python program to update a dictionary with the values from a dictionary list
Given a dictionary and dictionary list, update the dictionary with dictionary list values. Input : test_dict = {"Gfg" : 2, "is" : 1, "Best" : 3}, dict_list = [{'for' : 3, 'all' : 7}, {'and' : 1, 'CS' : 9}] Output : {'Gfg': 2, 'is': 1, 'Best': 3, 'for': 3, 'all': 7, 'and': 1, 'CS': 9} Explanation : All dictionary keys updated in single dictionary. I
8 min read
Python - Append Dictionary Keys and Values ( In order ) in dictionary
Given a dictionary, perform append of keys followed by values in list. Input : test_dict = {"Gfg" : 1, "is" : 2, "Best" : 3} Output : ['Gfg', 'is', 'Best', 1, 2, 3] Explanation : All the keys before all the values in list. Input : test_dict = {"Gfg" : 1, "Best" : 3} Output : ['Gfg', 'Best', 1, 3] Explanation : All the keys before all the values in
5 min read
Python - Filter dictionary values in heterogeneous dictionary
Sometimes, while working with Python dictionaries, we can have a problem in which we need to filter out certain values based on certain conditions on a particular type, e.g all values smaller than K. This task becomes complex when dictionary values can be heterogeneous. This kind of problem can have applications across many domains. Let's discuss c
6 min read
Convert Dictionary Value list to Dictionary List Python
Sometimes, while working with Python Dictionaries, we can have a problem in which we need to convert dictionary list to nested records dictionary taking each index of dictionary list value and flattening it. This kind of problem can have application in many domains. Let's discuss certain ways in which this task can be performed. Input : test_list =
9 min read
Python - Split Dictionary values on size limit of values
Given a dictionary with string values, the task is to write a python program to split values if the size of string exceeds K. Input : {1 : "Geeksforgeeks", 2 : "best for", 3 : "all geeks"}, limit = 5Output : {1: 'Geeks', 2: 'forge', 3: 'eks', 4: 'best ', 5: 'for', 6: 'all g', 7: 'eeks'}Explanation : All string values are capped till length 5. New v
8 min read
Python - Extract Unique values dictionary values
Sometimes, while working with data, we can have problem in which we need to perform the extraction of only unique values from dictionary values list. This can have application in many domains such as web development. Lets discuss certain ways in which this task can be performed. Extract Unique values dictionary values Using sorted() + set comprehen
7 min read
Python - Test for Even values dictionary values lists
Given a dictionary with lists as values, map Boolean values depending upon all values in List are Even or not. Input : {"Gfg" : [6, 8, 10], "is" : [8, 10, 12, 16], "Best" : [10, 16, 14, 6]} Output : {'Gfg': True, 'is': True, 'Best': True} Explanation : All lists have even numbers. Input : {"Gfg" : [6, 5, 10], "is" : [8, 10, 11, 16], "Best" : [10, 1
8 min read
Python - Remove duplicate values in dictionary
Sometimes, while working with Python dictionaries, we can have problem in which we need to perform the removal of all the duplicate values of dictionary, and we are not concerned if any key get removed in the process. This kind of application can occur in school programming and day-day programming. Let's discuss certain ways in which this task can
8 min read
Python - Extract Dictionary values list to List
Sometimes, while working with dictionary records, we can have problems in which we need to extract all the dictionary values into a single separate list. This can have possible application in data domains and web-development. Lets discuss certain ways in which this task can be performed. Method #1 : Using map() + generator expression The combinatio
5 min read
three90RightbarBannerImg