Open In App

Python - Remove digits from Dictionary String Values List

Last Updated : 28 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

We are given dictionary we need to remove digits from the dictionary string value list. For example, we are given a dictionary that contains strings values d = {'key1': ['abc1', 'def2', 'ghi3'], 'key2': ['xyz4', 'lmn5']} we need to remove digits from dictionary so that resultant output becomes {'key1': ['abc', 'def', 'ghi'], 'key2': ['xyz', 'lmn']}.

Using re.sub()

This method uses regular expressions to remove digits and list comprehension to apply it to each string in the list.


Output
{'key1': ['abc', 'def', 'ghi'], 'key2': ['xyz', 'lmn']}

Explanation:

  • Removing Digits with Regular Expressions code iterates through each list in the dictionary, applying re.sub(r'\d+', '', item) to remove all digits from each string using a regular expression (\d+ matches one or more digits).
  • Updating the Dictionary updates strings with digits removed, replace the original strings in the dictionary for each key and final dictionary is printed without digits in any of the string values.

Using str.translate() and str.maketrans()

This method uses str.translate() in combination with str.maketrans() to remove digits from each string.


Output
{'key1': ['abc', 'def', 'ghi'], 'key2': ['xyz', 'lmn']}

Explanation:

  • Translation Table str.maketrans('', '', '0123456789') creates a table to remove digits from strings.
  • Remove Digits translate() is applied to each string in the dictionary’s lists to remove the digits.

Using str.join()

This method iterates through each character in the string and removes the digits using a list comprehension.


Output
{'key1': ['abc', 'def', 'ghi'], 'key2': ['xyz', 'lmn']}

Explanation:

  • List comprehension filters out digits from each string in the dictionary’s lists.
  • Dictionary is updated with the new lists of strings without digits

Using str.replace()

We can use str.replace() in a loop to replace each digit with an empty string.


Output
{'key1': ['abc', 'def', 'ghi'], 'key2': ['xyz', 'lmn']}

Explanation:

  • replace() method is used to remove specific digits (1, 2, 3, 4, 5) from each string in the dictionary's lists by replacing them with an empty string.
  • Dictionary is updated with the modified strings, where the specified digits are removed from each string in the list.

Next Article

Similar Reads