Python Methods to Remove Spaces from Dictionary Values

By | December 2, 2024

In Python, dictionary is a collection which is unordered, changeable and indexed. Dictionaries are written with curly brackets, and they have keys and values. It is used to hash a particular key. Let’s see how to remove spaces from dictionary values in Python.

Method #1:
Using translate() function here we visit each value one by one and remove space with the none. Here translate function takes parameter 32, none where 32 is ASCII value of space ‘ ‘ and replaces it with none.

# Python program to remove spaces from values

# creating a dictionary of type string
Product_list = {'P01': ' D B M S ', 'P02': 'O  S', 
                'P03': ' Soft Computing '} 

# removing spaces from values and storing them in the same dictionary
Product_list = {x: y.translate({32: None}) for x, y in Product_list.items()}

# printing the new dictionary
print("New dictionary:", Product_list)

Output :

New dictionary: {'P01': 'DBMS', 'P02': 'OS', 'P03': 'SoftComputing'} 

Method #2:
Using replace() function. In this method, we visit each value in dictionary one by one and replace all spaces in key with no space. This function takes as argument space and second non-space.

# Python program to remove spaces from values

# creating a dictionary of type string
Product_list = {'P01': ' D B M S ', 'P02': 'O  S', 
                'P03': ' Soft Computing '} 

# removing spaces from values and storing them in the same dictionary
Product_list = {x: y.replace(' ', '') for x, y in Product_list.items()}

# printing the new dictionary
print("New dictionary:", Product_list)

Output :

New dictionary: {'P01': 'DBMS', 'P02': 'OS', 'P03': 'SoftComputing'}
Author: Mithlesh Upadhyay

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.