Skip to content
Related Articles

Related Articles

Python | Sort the list alphabetically in a dictionary
  • Last Updated : 28 Jan, 2019

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:




# 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)
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:






# 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)
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:




# 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)
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]}

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up
Recommended Articles
Page :