Python | Sort the list alphabetically in a dictionary

In Python Dictionary is quite a useful data structure, which is usually used to hash a particular key with value, so that they can be retrieved efficiently.

Let’s see how to sort the list alphabetically in a dictionary.

Example #1:



filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to sort the list 
# alphabetically in a dictionary
dict ={
    "L1":[87, 34, 56, 12],
    "L2":[23, 00, 30, 10],
    "L3":[1, 6, 2, 9],
    "L4":[40, 34, 21, 67]
}
  
print("\nBefore Sorting: ")
for x in dict.items():
    print(x)
  
print("\nAfter Sorting: ")
  
for i, j in dict.items():
    sorted_dict ={i:sorted(j)}
    print(sorted_dict)

chevron_right


Output:

Before Sorting: 
('L2', [23, 0, 30, 10])
('L3', [1, 6, 2, 9])
('L4', [40, 34, 21, 67])
('L1', [87, 34, 56, 12])

After Sorting: 
{'L2': [0, 10, 23, 30]}
{'L3': [1, 2, 6, 9]}
{'L4': [21, 34, 40, 67]}
{'L1': [12, 34, 56, 87]}

 
Example #2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to sort the list 
# alphabetically in a dictionary
  
dict ={
    "L1":["Geeks", "for", "Geeks"],
    "L2":["A", "computer", "science"],
    "L3":["portal", "for", "geeks"],
}
  
print("\nBefore Sorting: ")
for x in dict.items():
    print(x)
  
print("\nAfter Sorting: ")
for i, j in dict.items():
    sorted_dict ={i:sorted(j)}
    print(sorted_dict)

chevron_right


Output:

Before Sorting: 
('L3', ['portal', 'for', 'geeks'])
('L1', ['Geeks', 'for', 'Geeks'])
('L2', ['A', 'computer', 'science'])

After Sorting: 
{'L3': ['for', 'geeks', 'portal']}
{'L1': ['Geeks', 'Geeks', 'for']}
{'L2': ['A', 'computer', 'science']}

 
Example #3:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to sort the list 
# alphabetically in a dictionary
dict={
    "L1":[87,34,56,12],
    "L2":[23,00,30,10],
    "L3":[1,6,2,9],
    "L4":[40,34,21,67]
}
  
print("\nBefore Sorting: ")
for x in dict.items():
    print(x)
  
sorted_dict = {i: sorted(j) for i, j in dict.items()}
print("\nAfter Sorting: ", sorted_dict)

chevron_right


Output:

Before Sorting: 
('L1', [87, 34, 56, 12])
('L2', [23, 0, 30, 10])
('L3', [1, 6, 2, 9])
('L4', [40, 34, 21, 67])

After Sorting:  {'L1': [12, 34, 56, 87], 
                 'L2': [0, 10, 23, 30],
                 'L3': [1, 2, 6, 9], 
                 'L4': [21, 34, 40, 67]}


My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.