w3resource

Python: Remove spaces from dictionary keys

Python dictionary: Exercise-29 with Solution

Write a Python program to remove spaces from dictionary keys.

Visual Presentation:

Python Dictionary: Remove spaces from dictionary keys.

Sample Solution:

Python Code:

# Create a dictionary 'student_list' with keys containing extra spaces and associated lists of subjects.
student_list = {'S  001': ['Math', 'Science'], 'S    002': ['Math', 'English']}

# Print a message indicating the start of the code section.
print("Original dictionary: ", student_list)

# Use a dictionary comprehension to create a new dictionary 'student_dict'.
# Iterate through the key-value pairs in 'student_list'.
# Remove extra spaces from the keys using the 'translate' method with a translation table.
student_dict = {x.translate({32: None}): y for x, y in student_list.items()}

# Print a message indicating the start of the new dictionary section.
print("New dictionary: ", student_dict) 

Sample Output:

Original dictionary:  {'S  001': ['Math', 'Science'], 'S    002': ['Math', 'English']}
New dictionary:  {'S001': ['Math', 'Science'], 'S002': ['Math', 'English']} 

Python Code Editor:

Previous: Write a Python program to sort a list alphabetically in a dictionary.
Next: Write a Python program to get the top three items in a shop.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-exercises/dictionary/python-data-type-dictionary-exercise-29.php