OMDb API ordering items python dictionary

2

I need to make a program that given a given name, return the movie name and the year it was released using the api OMDb, and sort by the release year. I managed to list the movies but I can not 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 it wrong, if anyone 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'])
    
asked by anonymous 15.11.2018 / 22:35

1 answer

1

Use the sorted() sort function, it allows you to pass a key= parameter containing a function that is used to set the sort key.

In the case we can use operator.itemgetter to create a function that extracts one or more items from the object to be sorted, which would be perfect to move to sorted() :

import operator
for i in sorted(dic['Search'], key=operator.itemgetter('Year')):
    print("Titulo:", i['Title'])
    print("Ano:", i['Year'])
    
16.11.2018 / 00:08