Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python - Remove Disjoint Tuple Keys from Dictionary
Next article icon

Remove Spaces from Dictionary Keys – Python

Last Updated : 27 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Table of Content

  • Using pop()
  • Using map() and dict()
  • Using collections.OrderedDict (For Ordered Dictionaries)

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) 

Output
OrderedDict({'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.


Next Article
Python - Remove Disjoint Tuple Keys from Dictionary
author
ankit15697
Improve
Article Tags :
  • Python
  • Python Programs
  • Python dictionary-programs
  • python-dict
Practice Tags :
  • python
  • python-dict

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
  • Python - Remove Multiple Keys from Dictionary
    We are given a dictionary and our task is to remove multiple keys from the dictionary. For example, consider a dictionary d = {'a': 1, 'b': 2, 'c': 3, 'd': 4} where we want to remove the keys 'b' and 'd', then the output will be {'a': 1, 'c': 3}. Let's explore different methods to remove multiple ke
    3 min read
  • Remove Keys from Dictionary Starting with K - Python
    We are given a dictionary we need to remove the Keys which are starting with K. For example we are give a dictionary d = {'Key1': 'value1', 'Key2': 'value2', 'other_Key': 'value3'} so that the output should be {'other_Key': 'value3'} Using Dictionary ComprehensionUsing dictionary comprehension we ca
    3 min read
  • Python Remove Item from Dictionary by Value
    We are given a dictionary and our task is to remove key-value pairs where the value matches a specified target. This can be done using various approaches, such as dictionary comprehension or iterating through the dictionary. For example: d = {"a": 10, "b": 20, "c": 10, "d": 30} and we have to remove
    3 min read
  • Python Remove Item from Dictionary by Key
    Dictionaries in Python store data as key-value pairs. Often, we need to remove a specific key-value pair to modify or clean the dictionary. For instance, consider the dictionary d = {'a': 1, 'b': 2, 'c': 3}; we might want to remove the key 'b'. Let's explore different methods to achieve this. Using
    3 min read
  • Remove a Key from a Python Dictionary Using loop
    Sometimes, we need to remove specific keys while iterating through the dictionary. For example, consider the dictionary d = {'a': 1, 'b': 2, 'c': 3}. If we want to remove the key 'b', we need to handle this efficiently, especially to avoid issues like modifying the dictionary during iteration. Let's
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences