Python: Sort a list alphabetically in a dictionary
Write a Python program to sort a list alphabetically in a dictionary.
Sample Solution:
Python Code:
# Create a dictionary 'num' with keys 'n1', 'n2', and 'n3', and associated lists of numbers as values.
num = {'n1': [2, 3, 1], 'n2': [5, 1, 2], 'n3': [3, 2, 4]}
# Use a dictionary comprehension to create a new dictionary 'sorted_dict'.
# Iterate through the key-value pairs in 'num' and sort the lists of numbers ('y') for each key ('x').
sorted_dict = {x: sorted(y) for x, y in num.items()}
# Print the 'sorted_dict' dictionary, which contains the same keys with sorted lists of numbers as values.
print(sorted_dict)
Sample Output:
{'n1': [1, 2, 3], 'n2': [1, 2, 5], 'n3': [2, 3, 4]}
Python Code Editor:
Previous: Write a Python program to convert a list into a nested dictionary of keys.
Next: Write a Python program to remove spaces from dictionary keys.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics