2011-02-19 56 views
4

我想对Facebook的Graph API返回的朋友列表进行排序。排序后的结果需要按名称的字母顺序排列。如何按字母顺序排列单个键上的字典数组?

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

其他注意事项:我使用的是Google App Engine,它使用Python 2.5.x.

+0

谷歌App Engine的使用Python 2.5:http://code.google.com/appengine/docs/python/overview.html – 2011-02-19 13:35:41

+0

对不起,我的错字。 – 2011-02-21 22:52:17

回答

-1

如果你的列表被称为A,你可以用这种方式使用排序是:

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

8
sorted(flist, key=lambda friend: friend["name"]) 
+0

这似乎并不奏效。由于在Google App Engine上运行,我应该注意到我在Python 1.5.x上。 – 2011-02-19 05:11:32

+0

list.sort()中的`sorted()`函数和`key`参数都需要版本2.4和更新版本。我不知道@charleyc的方法是否适用于1.5.x版本。 – MHC 2011-02-19 05:28:19

3
import operator 

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

此外,itemgetter可以采取一些参数,并返回这些项目的元组,所以你可以排序在数字键的是这样的:

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

sorted函数返回一个新的排序列表。如果要排序的位置列表,请使用:

my_list.sort(key=operator.itemgetter("name"))