Python中如何对字典数组进行排序?

3
使用以下代码:
arr = [{"name":"joe", "hotdogs":5},{"name":"april", "hotdogs":5},{"name":"ryan", "hot dogs":8}]

如何在Python中对数组进行排序,使得字典按名称排序?

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

如何应用某些函数对数组中的字典进行排序?

你已经有17个问题了;现在是时候学习如何使用Markdown格式化问题了。 - rds
这是你实际使用的数据结构,还是一个简化的例子? - Colonel Panic
3个回答

6

就像这样:

arr.sort(key=operator.itemgetter('name'))

import operator - Rescommunes

1

喜欢这个答案,因为它还提供了一些背景信息。 - Dimitrios Mistriotis

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

1
虽然 OrderedDict 可以保留顺序,但它不能与该调用语法一起使用。例如,尝试 collections.OrderedDict(april=5, ryan=8, joe=5)。问题在于该类接收到一个无序的关键字参数字典。 - DSM
很遗憾。谢谢 DSM,我不知道那个。 - Colonel Panic

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接