-1

I want to sort this dictionary according to age

I have tried some ways to sort this like create a list of the age the sort that but then i won't able to assign the age to its corresonding index


students = {
    'a': {
        "age":18,
        "class": "IV"
    },
    'b': {
        "age":19,
        "class": "IV"
    },
    'c': {
        "age":17,
        "class": "IV"
    },
    'd': {
        "age":17.5,
        "class": "IV"
    },
    'e': {
        "age":19.5,
        "class": "IV"
    },
}
Zach Young
  • 10,137
  • 4
  • 32
  • 53

3 Answers3

1

You can do it with a dictionary comprehension:

{k: v for k, v in sorted(students.items(), key=lambda i: i[1]['age'])}

Output:

{'c': {'age': 17, 'class': 'IV'},
 'd': {'age': 17.5, 'class': 'IV'},
 'a': {'age': 18, 'class': 'IV'},
 'b': {'age': 19, 'class': 'IV'},
 'e': {'age': 19.5, 'class': 'IV'}}
Nin17
  • 2,821
  • 2
  • 4
  • 14
1

Try using the builtin sorted function.

students_sorted = dict(sorted(students.items(), key=lambda x: x[1]["age"]))

students_sorted:

{
  'c': {'age': 17, 'class': 'IV'}, 
  'd': {'age': 17.5, 'class': 'IV'},
  'a': {'age': 18, 'class': 'IV'}, 
  'b': {'age': 19, 'class': 'IV'}, 
  'e': {'age': 19.5, 'class': 'IV'}
}
Alexander
  • 16,091
  • 5
  • 13
  • 29
1

first you can to sort the key/value pairs of your dict by a custom sort key function and then put it back together

sorted_students = {
    key: value for key, value in sorted(
        students.items(), key=lambda item: item[1]['age']
    )
}
Raphael
  • 1,731
  • 2
  • 7
  • 23