3

With the following

Code

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

How to in python sort the elements of the array such as the dicts are sorted by name?

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

How to apply some function to sort the dicts in the array?

2
  • You have already 17 questions; it is high time you learn how to format questions with markdown. Commented Mar 3, 2013 at 17:06
  • Is that your actual data structure, or a simplified example? Commented Mar 3, 2013 at 17:24

3 Answers 3

6

Like this:

arr.sort(key=operator.itemgetter('name'))
Sign up to request clarification or add additional context in comments.

1 Comment

import operator
1

Have a look at the following web page: http://wiki.python.org/moin/HowTo/Sorting/

1 Comment

Liked this answer as gave also some context.
0

How about

>>> import collections
>>> collections.OrderedDict(april=5, joe=5, ryan=8)
OrderedDict([('april', 5), ('joe', 5), ('ryan', 8)]

Or per DSM's comment

>>> collections.OrderedDict([('april', 5), ('joe', 5), ('ryan', 8)])
OrderedDict([('april', 5), ('joe', 5), ('ryan', 8)])

2 Comments

While OrderedDict does preserve order, it can't be used with that call syntax. For example, try collections.OrderedDict(april=5, ryan=8, joe=5). The problem is that the class gets passed an unordered dictionary of keyword arguments.
Lame. Thanks DSM, I didn't know that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.