w3resource

Python: Remove spaces from dictionary keys


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.



Follow us on Facebook and Twitter for latest update.