![]() |
VOOZH | about |
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.
We can use dictionary comprehension to iterate over the original dictionary and create a new dictionary with modified keys.
{'firstname': 'Nikki', 'lastname': 'Smith', 'age': 30}
Explanation:
Let's explore some more ways to remove spaces from dictionary keys.
Table of Content
If we prefer to modify the dictionary in place, we can use a for loop with pop() method to remove spaces from the keys.
{'firstname': 'Nikki', 'lastname': 'Smith', 'age': 30}
Explanation:
map() function can be combined with dict() to create a new dictionary with modified keys.
{'firstname': 'Nikki', 'lastname': 'Smith', 'age': 30}
Explanation:
If maintaining the order of elements is important, we can use collections.OrderedDict to create a new dictionary with modified keys.
OrderedDict({'firstname': 'Nikki', 'lastname': 'Smith', 'age': 30})
Explanation: