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"}]
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"}]
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'}]