0

So, i am making a movie search cli app for educational reasons.

I am using tabulate to get a pretty table

>>> python movies.py
Please enter a movie name: sonic
+--------+--------------------+--------+
|      1 | Sonic the Hedgehog |   2020 |
|      0 | Oasis: Supersonic  |   2016 |
|--------+--------------------+--------|
|   SlNo | Title              |   Year |
+--------+--------------------+--------+

Here is the code i used:

# This is a wrapper for my API that scrapes Yify (yts.mx)

# Import the API
from YifyAPI.yify import search_yify as search

# Import the table
from tabulate import tabulate

# Import other utilities
import click, json


get_results = search(input('Please enter a movie name: '))
count = -1
table = []
for a in get_results:
    count += 1
    entry = [count, a['title'], a['year']]
    table.append(entry)
headers = ['SlNo', "Title", "Year"]
table = tabulate(table, headers, tablefmt='psql')
table = '\n'.join(table.split('\n')[::-1])
click.echo(table)

As you can see in the above code, i have a 2 dimensional list, and i want to sort each movie by using the 3rd item in each sub list, which is the year the movie was released in. Is there any easy and pythonic way to do this? It is possible to convert the year to an integer if it is needed. If possible i want to sort it by the most recent movie to the oldest. So it should be in a descending order.

Arjix
  • 146
  • 9

1 Answers1

0

Well, i dug a little in stackoverflow questions and found the most suitable answer for me: https://stackoverflow.com/a/7588949/13077523

From the Python documentation wiki, I think you can do:

a = ([[1, 2, 3], [4, 5, 6], [0, 0, 1]]); 
a = sorted(a, key=lambda a_entry: a_entry[1]) 
print a
The output is:

[[[0, 0, 1], [1, 2, 3], [4, 5, 6]]]

But what i instead did is:

get_results = search(input('Please enter a movie name: '))
get_results = sorted(get_results, key=lambda a_entry: a_entry['year'])
count = -1
table = []
for a in get_results:
    count += 1
    entry = [count, a['title'], a['year']]
    table.append(entry)

headers = ['SlNo', "Title", "Year"]
table = tabulate(table, headers, tablefmt='psql')
table = '\n'.join(table.split('\n')[::-1])
click.echo(table)

Which worked perfectly for me!

Arjix
  • 146
  • 9
  • This answer is not only pythonic but it is fast and easy to use. There are a lot of ways to achieve the same result but they either require an extra import or they require that I iterate over the list and make some changes until all the items are sorted correctly. – Arjix Jun 30 '20 at 00:44