Remove Spaces from Dictionary Keys - Python
Last Updated :
27 Jan, 2025
Sometimes, the keys in a dictionary may contain spaces, which can create issues while accessing or processing the data. For example, consider the dictionary d = {'first name': 'Nikki', 'last name': 'Smith'}. We may want to remove spaces from the keys to standardize the dictionary, resulting in {'firstname': 'Nikki', 'lastname': 'Smith'}. Let's explore different methods to efficiently remove spaces from dictionary keys.
Using Dictionary Comprehension
We can use dictionary comprehension to iterate over the original dictionary and create a new dictionary with modified keys.
Python
d = {'first name': 'Nikki', 'last name': 'Smith', 'age': 30}
# Remove spaces using dictionary comprehension
d = {k.replace(' ', ''): v for k, v in d.items()}
print(d)
Output{'firstname': 'Nikki', 'lastname': 'Smith', 'age': 30}
Explanation:
- We iterate over the key-value pairs using d.items().
- For each key k, we remove spaces using k.replace(' ', '').
- The resulting dictionary is assigned back to d.
Let's explore some more ways to remove spaces from dictionary keys.
Using pop()
If we prefer to modify the dictionary in place, we can use a for loop with pop() method to remove spaces from the keys.
Python
d = {'first name': 'Nikki', 'last name': 'Smith', 'age': 30}
# Remove spaces using a loop
for k in list(d.keys()):
new_key = k.replace(' ', '')
d[new_key] = d.pop(k)
print(d)
Output{'firstname': 'Nikki', 'lastname': 'Smith', 'age': 30}
Explanation:
- We first retrieve the list of keys using list(d.keys()) to avoid runtime errors during iteration.
- For each key, we use replace(' ', '') to create a new key without spaces.
- The pop() method removes the old key, and we add the value back to the dictionary using the new key.
Using map() and dict()
map() function can be combined with dict() to create a new dictionary with modified keys.
Python
d = {'first name': 'Nikki', 'last name': 'Smith', 'age': 30}
# Remove spaces using map() and dict()
d = dict(map(lambda kv: (kv[0].replace(' ', ''), kv[1]), d.items()))
print(d)
Output{'firstname': 'Nikki', 'lastname': 'Smith', 'age': 30}
Explanation:
- We use map() to iterate over the key-value pairs in d.items().
- For each pair, we modify the key using replace(' ', '').
- The dict() function converts the result back into a dictionary.
Using collections.OrderedDict (For Ordered Dictionaries)
If maintaining the order of elements is important, we can use collections.OrderedDict to create a new dictionary with modified keys.
Python
from collections import OrderedDict
d = {'first name': 'Nikki', 'last name': 'Smith', 'age': 30}
# Remove spaces using OrderedDict
d = OrderedDict((k.replace(' ', ''), v) for k, v in d.items())
print(d)
OutputOrderedDict({'firstname': 'Nikki', 'lastname': 'Smith', 'age': 30})
Explanation:
- We iterate over the key-value pairs in d.items() and modify the keys using replace(' ', '').
- The resulting dictionary is stored in an OrderedDict, preserving the insertion order.
Similar Reads
Remove Kth Key from Dictionary - Python We are given a dictionary we need to remove Kth key from the dictionary. For example, we are given a dictionary d = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3', 'key4': 'value4'} we need to remove the key2 so that the output should be {'key1': 'value1', 'key3': 'value3', 'key4': 'value4'}.
3 min read
Python - Remove Item from Dictionary There are situations where we might want to remove a specific key-value pair from a dictionary. For example, consider the dictionary d = {'x': 10, 'y': 20, 'z': 30}. If we need to remove the key 'y', there are multiple ways to achieve this. Let's discuss several methods to remove an item from a dict
3 min read
Python - Remove Disjoint Tuple Keys from Dictionary We are given a dictionary we need to remove the Disjoint Tuple key from it. For example we are given a dictionary d = {('a', 'b'): 1, ('c',): 2, ('d', 'e'): 3, 'f': 4} we need to remove all the disjoint tuple so that the output should be { }. We can use multiple methods like dictionary comprehension
3 min read
Python - Remove K valued key from Nested Dictionary We are given a nested dictionary we need to remove K valued key. For example, we are given a nested dictionary d = { "a": 1, "b": {"c": 2,"d": {"e": 3,"f": 1},"g": 1},"h": [1, {"i": 1, "j": 4}]} we need to remove K valued key ( in our case we took k value as 1 ) from it so that the output should be
3 min read
Python - Remove Top level from Dictionary Sometimes, while working with Python Dictionaries, we can have nesting of dictionaries, with each key being single values dictionary. In this we need to remove the top level of dictionary. This can have application in data preprocessing. Lets discuss certain ways in which this task can be performed.
3 min read