Python: Sort a list alphabetically in a dictionary
Python dictionary: Exercise-28 with Solution
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.
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://198.211.115.131/python-exercises/dictionary/python-data-type-dictionary-exercise-28.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics