Remove Spaces from Dictionary Keys using Python

Dictionary keys with spaces can cause issues when accessing data programmatically. Python provides several methods to remove spaces from dictionary keys: creating a new dictionary, modifying existing keys, using dictionary comprehension, and handling nested dictionaries with recursion.

Method 1: Creating a New Dictionary

The simplest approach is to create a new dictionary with space-free keys while preserving the original values ?

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

test_dictionary = {"full name": "Aayush Yadav", "age": 12}
modified_dictionary = remove_spaces(test_dictionary)
print(modified_dictionary)
{'fullname': 'Aayush Yadav', 'age': 12}

Method 2: Modifying the Existing Dictionary

Instead of creating a new dictionary, you can modify the existing one by using pop() to remove old keys and add new ones ?

def remove_spaces(dictionary):
    for key in list(dictionary.keys()):
        if " " in key:
            new_key = key.replace(" ", "")
            dictionary[new_key] = dictionary.pop(key)
    return dictionary

our_dictionary = {"full name": "Aayush Singh", "father name": "Yadav"}
remove_spaces(our_dictionary)
print(our_dictionary)
{'fullname': 'Aayush Singh', 'fathername': 'Yadav'}

Method 3: Using Dictionary Comprehension

Dictionary comprehension provides a concise one-liner solution ?

def remove_spaces_compact(dictionary):
    return {key.replace(" ", ""): value for key, value in dictionary.items()}

my_dictionary = {"full name": "Aayush Singh", "father name": "Yadav"}
modified_dictionary = remove_spaces_compact(my_dictionary)
print(modified_dictionary)
{'fullname': 'Aayush Singh', 'fathername': 'Yadav'}

Method 4: Handling Nested Dictionaries with Recursion

For nested dictionaries, use recursion to remove spaces from keys at all levels ?

def remove_spaces_recursive(dictionary):
    new_dictionary = {}
    for key, value in dictionary.items():
        if isinstance(value, dict):
            value = remove_spaces_recursive(value)
        new_key = key.replace(" ", "")
        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_recursive(test_dictionary)
print(modified_dictionary)
{'fullname': 'Aayush Singh', 'fathername': 'Yadav', 'details': {'age': 12, 'bloodgroup': 'O-'}}

Comparison

Method Original Preserved? Memory Usage Best For
New Dictionary Yes Higher When original must be preserved
Modify Existing No Lower When original can be modified
Dict Comprehension Yes Higher Concise, readable code
Recursive Yes Higher Nested dictionaries

Conclusion

Use dictionary comprehension for simple cases, modify existing dictionaries for memory efficiency, and apply recursion for nested structures. Choose the method based on whether you need to preserve the original dictionary and handle nested data.

Updated on: 2026-03-27T10:45:12+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements