Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting array of dicts python?

Tags:

python

With the following

Code

arr = [{"name":"joe", "hotdogs":5},{"name":"april", "hotdogs":5},{"name":"ryan", "hot dogs":8}]

How to in python sort the elements of the array such as the dicts are sorted by name?

arr = [{"name":"april", "hotdogs":5},{"name":"joe", "hotdogs":5},{"name":"ryan", "hotdogs":8}]

How to apply some function to sort the dicts in the array?

like image 718
Setsuna Avatar asked Dec 11 '25 08:12

Setsuna


2 Answers

Like this:

arr.sort(key=operator.itemgetter('name'))
like image 133
JBernardo Avatar answered Dec 13 '25 21:12

JBernardo


Have a look at the following web page: http://wiki.python.org/moin/HowTo/Sorting/

like image 33
Steven Graham Avatar answered Dec 13 '25 22:12

Steven Graham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!