How to Sort an Array of Dictionaries in Python?

Estimated read time 2 min read

To sort an array of dictionaries in Python, you can use the sorted() function with a lambda function as the key argument. The lambda function should specify the sorting key for each dictionary.

Here’s an example implementation:

# Define an array of dictionaries
my_array = [
    {'name': 'Alice', 'age': 25},
    {'name': 'Bob', 'age': 30},
    {'name': 'Charlie', 'age': 20},
    {'name': 'David', 'age': 35}
]

# Sort the array of dictionaries based on the 'age' key of each dictionary
sorted_array = sorted(my_array, key=lambda x: x['age'])

# Print the sorted array
print(sorted_array)

In this example, we define an array my_array of dictionaries. We use the sorted() function to sort the array based on the ‘age’ key of each dictionary. We use a lambda function lambda x: x['age'] as the key argument to specify the sorting key for each dictionary. The lambda function selects the value associated with the ‘age’ key of each dictionary, which is used to determine the order in which the dictionaries are sorted. We then assign the sorted array to the sorted_array variable and print it.

Note that the sorted() function returns a new sorted array, and does not modify the original array. If you want to modify the original array in place, you can use the sort() method of the array of dictionaries instead:

# Sort the array of dictionaries in place based on the 'name' key of each dictionary
my_array.sort(key=lambda x: x['name'])

# Print the modified array
print(my_array)

In this example, we use the sort() method of the array of dictionaries to sort the array in place based on the ‘name’ key of each dictionary. We use a lambda function lambda x: x['name'] as the key argument to specify the sorting key for each dictionary. The lambda function selects the value associated with the ‘name’ key of each dictionary, which is used to determine the order in which the dictionaries are sorted. We then print the modified array.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply