How to alphabetically sort an array of dictionaries on one key?

I want to sort the list of friends returned by the Facebook Graph API. The result after sorting should be in alphabetical order of friends by name.

[ { "name": "Joe Smith", "id": "6500000" }, { "name": "Andrew Smith", "id": "82000" }, { "name": "Dora Smith", "id": "97000000" }, { "name": "Jacki Smith", "id": "107000" } ] 

Additional notes: I am running the Google App Engine, which uses Python 2.5.x.

+4
source share
3 answers

If your list is called A , you can sort it this way using:

A.sort(cmp = lambda x,y: cmp(x["name"],y["name"]))

-1
source
 sorted(flist, key=lambda friend: friend["name"]) 
+8
source
 import operator sorted(my_list, key=operator.itemgetter("name")) 

In addition, itemgetter can take several arguments and returns a tuple of these elements, so you can sort by several keys as follows:

 sorted(my_list, key=operator.itemgetter("name", "age", "other_thing")) 

The sorted function returns a new sorted list. If you want to sort the list in place, use:

 my_list.sort(key=operator.itemgetter("name")) 
+3
source

Source: https://habr.com/ru/post/1340412/


All Articles