使用以下
代码
arr = [{"name":"joe", "hotdogs":5},{"name":"april", "hotdogs":5},{"name":"ryan", "hot dogs":8}]
如何在python中对数组中的元素进行排序,例如dicts按名称排序?
arr = [{"name":"april", "hotdogs":5},{"name":"joe", "hotdogs":5},{"name":"ryan", "hotdogs":8}]
如何应用某些函数对数组中的dicts进行排序?
答案 0 :(得分:5)
像这样:
arr.sort(key=operator.itemgetter('name'))
答案 1 :(得分:1)
答案 2 :(得分:0)
怎么样
>>> import collections
>>> collections.OrderedDict(april=5, joe=5, ryan=8)
OrderedDict([('april', 5), ('joe', 5), ('ryan', 8)]
或根据DSM的评论
>>> collections.OrderedDict([('april', 5), ('joe', 5), ('ryan', 8)])
OrderedDict([('april', 5), ('joe', 5), ('ryan', 8)])