OMDb API sorting items python dictionary
I need to make a program that given certain name, return the name of the movie and the year it was released using the OMDb api, and sort by the year of release. I managed to list the films but I am not able to sort by the year of release, because it is a dictionary, I have tried everything even the OrderedDict but it does not work or I am using wrong, if someone can help me I will be grateful.
import requests
import json
from operator import itemgetter
from collections import OrderedDict
def requisicao(nome):
try:
req = requests.get('http://www.omdbapi.com/?apikey=5b5be94f&type=movie&s='+nome)
return req
except:
print('Erro de conexão')
return None
while True:
nome = input('Digite o nome do filme ou EXIT para sair: ')
if nome == 'EXIT':
exit()
else:
result = requisicao(nome)
dic = json.loads(result.text)
#OrderedDict(sorted(dic.items(), key=lambda t: t[1]))
for i in dic['Search']:
print("Titulo: " + i['Title'] + "\n" "Ano: " + i['Year'])
2
Author: Marco Aurélio, 2018-11-15
1 answers
Use the sort function sorted()
, it allows you to pass a parameter key=
containing a function that serves to set the sort key.
In this case we can use operator.itemgetter
to create a function that extracts one or more items from the object to be ordered, which would be perfect to pass to the sorted()
:
import operator
for i in sorted(dic['Search'], key=operator.itemgetter('Year')):
print("Titulo:", i['Title'])
print("Ano:", i['Year'])
1
Author: nosklo, 2018-11-16 10:17:11