Omdb API sorting python dictionary items

Asked

Viewed 242 times

2

I need to make a program that given a given name, return the name of the film and the year it was released using the Omdb api, and sort by year of release. I managed to list the movies but I’m not able to sort through the year of release, because it’s a dictionary, I’ve tried everything even Ordereddict but it doesn’t work or I’m using it wrong, if anyone can help me I’ll 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'])

1 answer

1


Use the sort function sorted(), it allows you to pass a parameter key= containing a function that serves to define the sorting key.

In 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'])
  • Hello @nosklo. Try to detail more your answer, explain what it does.

  • @Joãomartins done, I hope it’s clearer

  • Gave it right, thank you very much @nosklo

Browser other questions tagged

You are not signed in. Login or sign up in order to post.