Python | Sort the list alphabetically in a dictionary
Last Updated :
12 Jul, 2023
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.
Sort a List Alphabetically in Python
In Python, Sorting a List Alphabetically is a typical activity that takes on added interest when working with a list contained within a dictionary. This article will examine various methods for sorting a list within a Python dictionary alphabetically. List comprehension, lambda functions, and techniques utilizing the sorted() function will all be covered.
- Using Sorted() Function
- Using List Comprehension
- Using Lambda Functions
Sort using Sorted() Function
The built-in sorted() function of Python enables us to Sort a List Alphabetically. This function and lambda functions can be used to order the list inside a dictionary.
Python3
my_dict = {
"L1": ["Red", "Green", "Yellow", "Blue"],
"L2": ["Violet", "Dark green", "Pink", "White"],
"L3": ["Black", "Aqua", "Beige", "Aqua"],
"L4": ["Alice Blue", "Cyan", "Gold", "Silver"]
}
print("Before Sorting:")
for key, value in my_dict.items():
print(key + ": " + str(value))
sorted_dict = {key: sorted(value) for key, value in my_dict.items()}
print("\nAfter Sorting:")
for key, value in sorted_dict.items():
print(key + ": " + str(value))
Output
Before Sorting:
L1: ['Red', 'Green', 'Yellow', 'Blue']
L2: ['Violet', 'Dark green', 'Pink', 'White']
L3: ['Black', 'Aqua', 'Beige', 'Aqua']
L4: ['Alice Blue', 'Cyan', 'Gold', 'Silver']
After Sorting:
L1: ['Blue', 'Green', 'Red', 'Yellow']
L2: ['Dark green', 'Pink', 'Violet', 'White']
L3: ['Aqua', 'Aqua', 'Beige', 'Black']
L4: ['Alice Blue', 'Cyan', 'Gold', 'Silver']
Time complexity: O(n*n), where n is the number of key-value pairs in the dictionary.
Auxiliary space: O(n), to store the keys and values in the dictionary.
Sort using List Comprehension
A quick approach to going through the dictionary, Sorting a List Alphabetically, and making a new dictionary is by LIst comprehension.
Python3
my_dict = {
"L1": ["Red", "Green", "Yellow", "Blue"],
"L2": ["Violet", "Dark green", "Pink", "White"],
"L3": ["Black", "Aqua", "Beige", "Aqua"],
"L4": ["Alice Blue", "Cyan", "Gold", "Silver"]
}
# Print the original dictionary
print("Before Sorting:")
for key, value in my_dict.items():
print(key + ": " + str(value))
# Sort the lists alphabetically within the dictionary using list comprehensions
sorted_dict = {key: sorted(value) for key, value in my_dict.items()}
# Print the sorted dictionary
print("\nAfter Sorting:")
for key, value in sorted_dict.items():
print(key + ": " + str(value))
Output
Before Sorting:
L1: ['Red', 'Green', 'Yellow', 'Blue']
L2: ['Violet', 'Dark green', 'Pink', 'White']
L3: ['Black', 'Aqua', 'Beige', 'Aqua']
L4: ['Alice Blue', 'Cyan', 'Gold', 'Silver']
After Sorting:
L1: ['Blue', 'Green', 'Red', 'Yellow']
L2: ['Dark green', 'Pink', 'Violet', 'White']
L3: ['Aqua', 'Aqua', 'Beige', 'Black']
L4: ['Alice Blue', 'Cyan', 'Gold', 'Silver']
Time Complexity: O(n*m log m), where 'm' is the length of the longest list of values in the dictionary.
Space Complexity: O(n), where 'n' is the number of key-value pairs in the dictionary.
Sort using Lambda Function
To Sort a List Alphabetically, Within the sorted() function, lambda functions provide an alternate method for specifying sorting criteria.
Python3
my_dict = {
"L1": ["Red", "Green", "Yellow", "Blue"],
"L2": ["Violet", "Dark green", "Pink", "White"],
"L3": ["Black", "Aqua", "Beige", "Aqua"],
"L4": ["Alice Blue", "Cyan", "Gold", "Silver"]
}
print("Before Sorting:")
for key, value in my_dict.items():
print(key + ": " + str(value))
sorted_dict = {key: sorted(value, key=lambda x: x.lower())
for key, value in my_dict.items()}
print("\nAfter Sorting:")
for key, value in sorted_dict.items():
print(key + ": " + str(value))
Output
Before Sorting:
L1: ['Red', 'Green', 'Yellow', 'Blue']
L2: ['Violet', 'Dark green', 'Pink', 'White']
L3: ['Black', 'Aqua', 'Beige', 'Aqua']
L4: ['Alice Blue', 'Cyan', 'Gold', 'Silver']
After Sorting:
L1: ['Blue', 'Green', 'Red', 'Yellow']
L2: ['Dark green', 'Pink', 'Violet', 'White']
L3: ['Aqua', 'Aqua', 'Beige', 'Black']
L4: ['Alice Blue', 'Cyan', 'Gold', 'Silver']
Time Complexity: O(n*m log m)
Space Complexity: O(n)
Similar Reads
How to Alphabetize a Dictionary in Python
Alphabetizing a dictionary in Python can be useful for various applications, such as data organization and reporting. In this article, we will explore different methods to alphabetize a dictionary by its keys or values.Dictionary OrderingIn Python, dictionaries are a powerful data structure that all
2 min read
Sort a list in Python without sort Function
Python Lists are a type of data structure that is mutable in nature. This means that we can modify the elements in the list. We can sort a list in Python using the inbuilt list sort() function. But in this article, we will learn how we can sort a list in a particular order without using the list sor
3 min read
Print anagrams together in Python using List and Dictionary
An anagram is a word or phrase formed by rearranging the letters of another word or phrase, using all the original letters exactly once. The task of grouping anagrams together in Python can be efficiently solved using lists and dictionaries. The key idea is to process each word by sorting its charac
2 min read
Python - Keys associated with value list in dictionary
Sometimes, while working with Python dictionaries, we can have a problem finding the key of a particular value in the value list. This problem is quite common and can have applications in many domains. Let us discuss certain ways in which we can Get Keys associated with Values in the Dictionary in P
4 min read
Difference between List and Dictionary in Python
Lists and Dictionaries in Python are inbuilt data structures that are used to store data. Lists are linear in nature whereas dictionaries stored the data in key-value pairs. In this article, we will see the difference between the two and find out the time complexities and space complexities which ar
6 min read
Sort Python Dictionary by Key or Value - Python
There are two elements in a Python dictionary-keys and values. You can sort the dictionary by keys, values, or both. In this article, we will discuss the methods of sorting dictionaries by key or value using Python.Sorting Dictionary By Key Using sort()In this example, we will sort the dictionary by
6 min read
How to Create a Dictionary in Python
The task of creating a dictionary in Python involves storing key-value pairs in a structured and efficient manner, enabling quick lookups and modifications. A dictionary is an unordered, mutable data structure where each key must be unique and immutable, while values can be of any data type. For exa
3 min read
How to Sort a Dictionary by Value in JavaScript ?
In JavaScript, dictionaries do not have a built-in method to sort them by their values. However, there are several approaches to achieve this functionality. Below are the possible Approaches: Table of Content Using Array.sort() with Object.entries()Using a custom sort functionUsing Array.sort() with
2 min read
How to Sort a Dictionary by Value in TypeScript ?
In TypeScript, dictionaries are objects that store key-value pairs. Sorting a dictionary by value involves arranging the key-value pairs based on the values in ascending or descending order. The below approaches can be used to accomplish this task: Table of Content Using Object.entries() and Array.s
2 min read
How to Sort a String Characters Alphabetically in Ruby?
This article focuses on discussing how to sort a string's characters alphabetically in Ruby. Using Chars and SortSyntax: sorted_string = string.chars.sort.join Example: In this example, the string is converted into an array of characters, and the sort method is used to sort the array. Ruby # Origina
2 min read