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.
# 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) |
Exit :
New dictionary: {’P03’:’ Soft Computing’, ’P01’:’ DBMS’, ’P02’ : ’OS’}
Shop
Best Python online courses for 2022
$FREE
Best laptop for Excel
$
Best laptop for Solidworks
$399+
Best laptop for Roblox
$399+
Best computer for crypto mining
$499+
Best laptop for Sims 4
$
Best laptop for Zoom
$499
Best laptop for Minecraft
$590
Latest questions
PythonStackOverflow
Common xlabel/ylabel for matplotlib subplots
1947 answers
PythonStackOverflow
Check if one list is a subset of another in Python
1173 answers
PythonStackOverflow
How to specify multiple return types using type-hints
1002 answers
PythonStackOverflow
Printing words vertically in Python
909 answers
PythonStackOverflow
Python Extract words from a given string
798 answers
PythonStackOverflow
Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?
606 answers
PythonStackOverflow
Python os.path.join () method
384 answers
PythonStackOverflow
Flake8: Ignore specific warning for entire file
360 answers
Wiki
Python | How to copy data from one Excel sheet to another
Common xlabel/ylabel for matplotlib subplots
Check if one list is a subset of another in Python
How to specify multiple return types using type-hints
Printing words vertically in Python
Python Extract words from a given string
Cyclic redundancy check in Python
Finding mean, median, mode in Python without libraries
Python add suffix / add prefix to strings in a list
Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?
Python - Move item to the end of the list
Python - Print list vertically