-1

there are 4 dictionaris in a list:

mylist = [{'name': 'c', 'age': 21}, {'name': 'b', 'age': 20}, {'name': 'd', 'age': 21}, {'name': 'a', 'age': 20}]

if I want to sort this by age, then I should use:

mylist.sort(key= lambda psn: psn['age'])

then output would be:

mylist = [{'name': 'b', 'age': 20}, {'name': 'a', 'age': 20}, {'name': 'c', 'age': 21}, {'name': 'd', 'age': 21}]

now! what if i want to sort this list by 'age' but if there were any same ages, then i sort just those persons by name ? in this list, 'a' and 'b' have same ages. and also 'c' and 'd' have same ages too. so how can i sort this list by 'age' but if there were any same ages sort them by 'name' ? (alphabetically)

should be this:

mylist = [{'name': 'a', 'age': 20}, {'name': 'b', 'age': 20}, {'name': 'c', 'age': 21}, {'name': 'd', 'age': 21}]
Amin Rzn
  • 1
  • 1

3 Answers3

0

Use the key argument of sorted function. To sort first by age and then by name you can return a tuple, something like this:

>>> list = [{'name': 'c', 'age': 21}, {'name': 'b', 'age': 20}, {'name': 'd', 'age': 21}, {'name': 'a', 'age': 20}]
>>> sorted(list, key=lambda x:  (x['age'],x['name']))
[{'age': 20, 'name': 'a'}, {'age': 20, 'name': 'b'}, {'age': 21, 'name': 'c'}, {'age': 21, 'name': 'd'}]
>>>

BTW, use a different name for your variable list 'cause it would hide built-in list.

dcg
  • 4,187
  • 1
  • 18
  • 32
0

If you want to also consider the name secondly, just return tuple (I use the word arr Instead of your list):

 sorted(arr, key=lambda x: (x['age'],x['name']))
adir abargil
  • 5,495
  • 3
  • 19
  • 29
0

You could make a composite key, e.g. using operator.itemgetter to make it more readable:

from operator import itemgetter

lst.sort(key=itemgetter("age", "name"))

Python's sorting algorithm Timsort also works well when sorting data in multiple rounds taking advantage of partial sorts (this would be more relevant if you wanted to sort by the second key in descending order for instance and a composite key is not so easily obtainable). It is even a recommended pattern in the sorting docs:

lst.sort(key=itemgetter("name"))
lst.sort(key=itemgetter("age"))  # stable wrt first run

Notice that you do the rounds in reverse order of priority.

user2390182
  • 72,016
  • 6
  • 67
  • 89