开发者

How to alphabetically sort array of dictionaries on single key?

I want to sort the list of friends returned by Facebook's Graph API. The result after sorting needs to be an 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 on Google App Engine, which uses Python 2.5.x.


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


import operator

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

Also, itemgetter can take a few arguments, and returns a tuple of those items, so you can sort on a number of keys like this:

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"))


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

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜