Python | Remove spaces from dictionary keys
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 keys in Python.
Method #1:
Using translate()
function here we visit each key 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 space from keys # creating a dictionary of type string Product_list = { 'P 01' : 'DBMS' , 'P 02' : 'OS' , 'P 0 3 ' : 'Soft Computing' } # removing spaces from keys # storing them in sam dictionary Product_list = { x.translate({ 32 : None }) : y for x, y in Product_list.items()} # printing new dictionary print ( " New dictionary : " , Product_list) |
New dictionary : {'P01': 'DBMS', 'P03': 'Soft Computing', 'P02': 'OS'}
Method #2:
Using replace()
function. In this method, we visit each key 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 space from keys # creating a dictionary of type string Product_list = { 'P 01' : 'DBMS' , 'P 02' : 'OS' , 'P 0 3 ' : 'Soft Computing' }; # removing spaces from keys # storing them in sam dictionary Product_list = {x.replace( ' ' , ''): v for x, v in Product_list.items()} # printing new dictionary print ( " New dictionary : " , Product_list) |
New dictionary : {'P03': 'Soft Computing', 'P01': 'DBMS', 'P02': 'OS'}
Recommended Posts:
- Python | Remove Keys from dictionary starting with K
- Python | Remove multiple keys from dictionary
- Python | Add new keys to a dictionary
- Python | Add keys to nested dictionary
- Python | Count keys with particular value in dictionary
- Python Dictionary | keys() method
- Python | Get dictionary keys as a list
- Python | Minimum value keys in Dictionary
- Python | Get the number of keys with given value N in dictionary
- Python | Get all tuple keys from dictionary
- Python | Get total keys in dictionary
- Python | Grouping dictionary keys by value
- Python | Remove spaces from a string
- Python dictionary with keys having multiple inputs
- Python | Unpacking dictionary keys into tuple
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.