Remove Spaces from Dictionary Keys using Python


Python is widely used platform for the purpose of Data Analysis, Web Development, AI and perform many different types of tasks with the help of automation. It is important for us to have knowledge about the different features of python. In this article, we are going to learn about the dictionary feature and how to remove space between keys using python. This feature is mainly used for the storage and retrieval of data as per need but sometimes there are chances of space in between the key values of the dictionary. This leads to errors while the user wants to have access to the data or even in the cases when the data is to be edited.

Different Methods of Removing Space

To ensure that no such issue is faced and to have a smooth−user experience we can remove spaces in between the keys in the dictionary. So, in this article we are going to learn about the different methods of how to remove spaces from the dictionary keys using python?

Establishing New Dictionary

One of the simplest methods to remove spaces is by simply creating a whole new dictionary. The steps to the same is by just selecting each value pair from the existing dictionary and create a new dictionary using the same values just by removing the spaces in between them. Let’s take an example to understand it in a better way: -

def remove_spaces(dictionary):
    modified_dictionary = {}
    for key, value in dictionary.items():
        new_key = key.replace(" ", "")  #removing space between keys
        modified_dictionary[new_key] = value
    return modified_dictionary

In the above code

  • The input of dictionary is given to a function called remove_spaces

  • All the new values are present in the modified_dictionary

  • To use the old values having space in between keys we can use items()

  • To remove all the spaces from the modified library, replace() is used.

To check whether the space is removed in between the keys, we can use the following dictionary: -

test_dictionary = {"full name": "Aayush Yadav", "age": 12} 
#This data is used just for example

We will then use remove_spaces and test_dictionary as the function and argument respectively

Example

def remove_spaces(dictionary):
    modified_dictionary = {}
    for key, value in dictionary.items():
        new_key = key.replace(" ", "")  #removing space between keys
        modified_dictionary[new_key] = value
    return modified_dictionary
test_dictionary = {"full name": "Aayush Yadav", "age": 12} 
#This data is used just for example
modified_dictionary = remove_spaces(test_dictionary)
#After the function and argument has been called
print(modified_dictionary)

Output

The output after performing all the above steps will be as follows:

{'fullname': 'Aayush Yadav', 'age': 12}

The space in between the full name was removed and thus we were successful in removing the spaces.

Editing Existing Dictionary

Under this method of removing spaces from keys, we do not create any new dictionary after removing spaces like the first method but instead we remove spaces in between keys from the existing dictionary. We will understand it in a better way through the following example:

def remove_spaces(dictionary):
    keys_to_remove = []
    for key in dictionary.keys():
        if " " in key:
            new_key = key.replace(" ", "") #removing space between keys
            dictionary[new_key] = dictionary.pop(key)
    return dictionary

The above code can be used to remove all the spaces in between keys and we can check the same by taking the following dictionary as an example: -

our_dictionary = {"full name": "Aayush Singh" , "Father name": "Yadav"}

Now we will use our_dictionary as the argument and remove_spaces as the function to make the changes.

Example

def remove_spaces(dictionary):
    keys_to_remove = []
    for key in dictionary.keys():
        if " " in key:
           new_key = key.replace(" ", "") #removing space between keys
           dictionary[new_key] = dictionary.pop(key)
    return dictionary
our_dictionary = {"full name": "Aayush Singh" , "Father name": "Yadav"}
remove_spaces(our_dictionary)
print(our_dictionary)

Output

The output after calling the argument and running the function is:

{'fullname': 'Aayush Singh', 'fathername': 'Yadav'}  

The space between full name and father name was successfully removed.

Using Dictionary Comprehension

This method is a different method than the other two methods explained above. In this method we create a new dictionary from a dictionary comprehension. The values of the keys are kept the same but the only change made is that the space in between the keys in rxemoved while transferring the data from dictionary comprehension to the new dictionary. We can use the following code to understand it in a more better way:

def no_spaces (dictionary): #From dictionary Comprehension
    return {key.replace(" ", ""): value for key, value in dictionary.items()}

To remove the space between the key values, we can use the replace() function and we can check the same by the following dictionary:

my_dictionary = {"full name": "Aayush Singh", "father name": "Yadav"}

We will then run my_dictionary as the argument and no_spaces as the function.

Example

def no_spaces (dictionary): #From dictionary Comprehension
    return {key.replace(" ", ""): value for key, value in dictionary.items()}
my_dictionary = {"full name": "Aayush Singh", "father name": "Yadav"}
modified_dictionary = no_spaces (my_dictionary)
print(modified_dictionary)

Output

The output in this case will be as follows:

{'fullname': 'Aayush Singh', 'fathername': 'Yadav'}

The space between full name and father name was removed and thus we were successful in removing the spaces.

Using Recursive Functions

This type of method is best suitable in the cases when one dictionary is present inside another dictionary (Nested Dictionary). In such a case we can use the recursive function to remove the spaces in between keys. We will understand it in a better way through the following example:

def remove_spaces (dictionary): 
    new_dictionary = {}
    for key, value in dictionary.items(): #For normal dictionary
        if isinstance(value, dict):  #for nested dictionary	
            value = remove_spaces (value)
        new_key = key.replace(" ", "") #removing space between keys
        new_dictionary[new_key] = value
    return new_dictionary

We will use the following example to test the code:

test_dictionary = {"full name": "Aayush Singh", "father name": "Yadav", "details": {"age": 12, "blood group": "O-"}}

Now we will call the argument test_dictionary and run the function remove_spaces:

Example

def remove_spaces (dictionary): 
    new_dictionary = {}
    for key, value in dictionary.items(): #For normal dictionary
        if isinstance(value, dict):  #for nested dictionary	
            value = remove_spaces (value)
        new_key = key.replace(" ", "") #removing space between keys
        new_dictionary[new_key] = value
    return new_dictionary
test_dictionary = {"full name": "Aayush Singh", "father name": "Yadav", "details": {"age": 12, "blood group": "O-"}}
modified_dictionary = remove_spaces (test_dictionary)
print(modified_dictionary)

Output

The output of the above example will be:

{'fullname': 'Aayush Singh', 'fathername': 'Yadav', 'details': {'age': 12, 'bloodgroup': 'O-'}}

The space between full name and father name was removed and thus we were successful in removing space using recursive function.

Conclusion

Python has many different purposes of use by many different people and thus there are chances that one might want to remove space in between the dictionary keys using python. So, this article describes different methods one might use to remove the space in between keys. The article includes all the coding that is to be done to remove the spacing in between keys and an example to make the method easier to understand

To prevent any error while running the code, make sure that the changes are not replicated in the other part of the code.

Updated on: 01-Aug-2023

439 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements