Python | Remove spaces from dictionary keys

| | | | | | | |

Let’s see how to remove spaces from dictionary keys in Python.

Method # 1:
Using the translate () function here we access each key one by one and remove the space without. Here the translate function takes parameter 32, none where 32 — The ASCII value of the space & # 39; & # 39; and replaces it with none.

# Python program to remove spaces from keys


# create a string dictionary

Product_list = { ’P 01’ : ’ DBMS’ , ’P 02’ : ’OS’ ,

’ P 0 3 ’ : ’ Soft Computing’ }


# remove spaces from keys
# store them in the sam dictionary

Product_list = {x.translate ({ 32 : None }): y

for x, y in Product_list.items ()}


# printing new dictionary

print ( "New dictionary:" , Product_list)

Exit:

 New dictionary: {’P01’:’ DBMS’, ’P03’:’ Soft Computing’, ’P02’:’ OS’} 

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

Exit :

 New dictionary: {’P03’:’ Soft Computing’, ’P01’:’ DBMS’, ’P02’ : ’OS’} 

# Python program to remove spaces from keys


# create a string dictionary

Product_list = { ’P 01’ : ’ DBMS’ , ’ P 02’ : ’OS’ ,

’P 0 3’ : ’Soft Computing’ };


# remove spaces from keys
# store them in the sam dictionary

Product_list = {x.replace ( ’’ , ’’): v

for x, v in Product_list.items ()}


# printing new dictionary

print ( "New dictionary:" , Product_list)