How to order a list alphabetically in python/mako

118 views Asked by At

so I have this (very stupid for most people I'd assume) question: I'm trying to modify a small template I found online and at one point they give the order to sort the list called movie by rating in descending order via this command: recently_added['movie'].sort(key=lambda m: m['rating'], reverse=True)

I'd like to sort this list alphabetically A to Z myself, but for the life of me can't figure out how to do it! Is it possible? I think I should be using .sorted() instead of .sort() but I'm not sure.

Thank you very much!

2

There are 2 answers

0
Robin Dillen On

The solution is to just remove key=lambda m: m['rating'], reverse=True I asssume. The key in the example denotes which value to use when comparing. In the example it's the rating of the movie, but you just want the name of the movie which is the default key(since those are the values of the list). The reversed=True just denotes wether to use < or >.

then onto the differences between sort and sorted see What is the difference between `sorted(list)` vs `list.sort()`?. ;TLDR sorted creates a copy, .sort() manipulates the original list.

0
itameio On

The list.sort() sorts alphabetically by default.

data = ['Elle', 'Miles', 'Kratos', 'Joel', 'Peter', 'Nathan']

data.sort()
print(data)

Output
['Elle', 'Joel', 'Kratos', 'Miles', 'Nathan', 'Peter']

A quick google search provided the reference https://appdividend.com/2021/06/02/how-to-sort-list-alphabetically-in-python/