w3resource

Python: Sort a list alphabetically in a dictionary


28. 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]}

For more Practice: Solve these Related Problems:

  • Write a Python program to sort the list values within a dictionary in alphabetical order.
  • Write a Python program to iterate over a dictionary and sort each list value alphabetically.
  • Write a Python program to use dictionary comprehension to return a new dictionary with sorted list values.
  • Write a Python program to implement a function that takes a dictionary of lists and sorts each list alphabetically.

Go to:


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.

Python Code Editor:

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.