0

The problem is to sort a list of dictionaries based on a specific key in each dictionary using Python. The input is a list of dictionaries, where each dictionary contains a set of key-value pairs. The desired output is the same list of dictionaries, but sorted based on the value of a specific key in each dictionary. For example, in the given list of dictionaries my_list:

my_list = [    {'name': 'Alice', 'age': 25},    {'name': 'Bob', 'age': 30},    {'name': 'Charlie', 'age': 20},    {'name': 'David', 'age': 35}]

We want to sort the dictionaries based on the value of the 'age' key in each dictionary. The expected output after sorting the list should be:

[    {'name': 'Charlie', 'age': 20},    {'name': 'Alice', 'age': 25},    {'name': 'Bob', 'age': 30},    {'name': 'David', 'age': 35}]

I tried to solve this problem like this, but it turned out to be wrong:

my_list = [
    {'name': 'Alice', 'age': 25},
    {'name': 'Bob', 'age': 30},
    {'name': 'Charlie', 'age': 20},
    {'name': 'David', 'age': 35}
]

sorted_list = sorted(my_list, key=lambda x: x['age'])
for i in range(len(sorted_list)):print(f"{sorted_list[i]['name']} - {sorted_list[i]['age']}")
jarmod
  • 71,565
  • 16
  • 115
  • 122
Zirsar
  • 1

0 Answers0