skip to Main Content

I’m new to Python and I’m trying to sort a list of dictionaries based on a specific key within each dictionary. The dictionaries have the following structure:

python
Copy code
data = [
    {'name': 'John', 'age': 25},
    {'name': 'Jane', 'age': 30},
    {'name': 'Alex', 'age': 20}
]

I want to sort the list of dictionaries based on the ‘age’ key in ascending order. How can I achieve this using Python?

Any help would be appreciated. Thank you!

2

Answers


  1. You can use the following code:

    data = [
        {'name': 'John', 'age': 25},
        {'name': 'Jane', 'age': 30},
        {'name': 'Alex', 'age': 20}
    ]
    
    sorted_data = sorted(data, key=lambda x: x['age'])
    
    print(sorted_data)
    
    Login or Signup to reply.
  2. Using the sorted() function with a custom sorting key

    sorted_data = sorted(data, key=lambda x: x['age'])
    
    print(sorted_data)
    

    Output

    [
        {'name': 'Alex', 'age': 20}, 
        {'name': 'John', 'age': 25}, 
        {'name': 'Jane', 'age': 30}
    ]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search