-1

How to sort this list of dict based on age using python

[{"age":10,"name":"a"},{"age":11,"name":"b"},{"age":10,"name":"c"},{"age":11,"name":"d"}]
petezurich
  • 9,280
  • 9
  • 43
  • 57
  • 2
    Does this answer your question? [How do I sort a list of dictionaries by a value of the dictionary?](https://stackoverflow.com/questions/72899/how-do-i-sort-a-list-of-dictionaries-by-a-value-of-the-dictionary) – Ghost Ops Oct 23 '21 at 12:20

1 Answers1

0

You can use sorted() and pass a key to denote that you want to sort by the age value in each dict.

data = [{"age":10,"name":"a"},{"age":11,"name":"b"},{"age":10,"name":"c"},{"age":11,"name":"d"}]

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

#[{'age': 10, 'name': 'a'}, {'age': 10, 'name': 'c'}, {'age': 11, 'name': 'b'}, {'age': 11, 'name': 'd'}]
PacketLoss
  • 5,561
  • 1
  • 9
  • 27