当缺少几个键时,通过解压缩dict来格式化字符串

时间:2017-01-31 20:58:35

标签: python api if-statement scrapy imdbpy

我正在尝试执行此代码,向我展示一些IMDB电影评级:

import json
import sys

import imdb
import sendgrid

NOTIFY_ABOVE_RATING = 7.5

SENDGRID_API_KEY = "API KEY GOES HERE"


def run_checker(scraped_movies):
    imdb_conn = imdb.IMDb()
    good_movies = []
    for scraped_movie in scraped_movies:
        imdb_movie = get_imdb_movie(imdb_conn, scraped_movie['name'])
        if imdb_movie['rating'] > NOTIFY_ABOVE_RATING:
            good_movies.append(imdb_movie)
    if good_movies:
        send_email(good_movies)


def get_imdb_movie(imdb_conn, movie_name):
    results = imdb_conn.search_movie(movie_name)
    movie = results[0]
    imdb_conn.update(movie)
    print("{title} => {rating}".format(**movie))
    return movie


def send_email(movies):
    sendgrid_client = sendgrid.SendGridClient(SENDGRID_API_KEY)
    message = sendgrid.Mail()
    message.add_to("trevor@example.com")
    message.set_from("no-reply@example.com")
    message.set_subject("Highly rated movies of the day")
    body = "High rated today:<br><br>"
    for movie in movies:
        body += "{title} => {rating}".format(**movie)
    message.set_html(body)
    sendgrid_client.send(message)
    print("Sent email with {} movie(s).".format(len(movies)))


if __name__ == '__main__':
    movies_json_file = sys.argv[1]
    with open(movies_json_file) as scraped_movies_file:
        movies = json.loads(scraped_movies_file.read())
    run_checker(movies)

但是它给我发了这个错误:

C:\Python27\Scripts>python check_imdb.py movies.json
T2 Trainspotting => 8.1
Sing => 7.3
Traceback (most recent call last):
  File "check_imdb.py", line 49, in <module>
    run_checker(movies)
  File "check_imdb.py", line 16, in run_checker
    imdb_movie = get_imdb_movie(imdb_conn, scraped_movie['name'])
  File "check_imdb.py", line 27, in get_imdb_movie
    print("{title} => {rating}".format(**movie))
KeyError: 'rating'

这是因为它正在尝试打印尚未评级的电影。 我尝试了if / else多次修复它,但没有成功。

1 个答案:

答案 0 :(得分:0)

问题是因为您的movie字典没有rating 。要解决此问题,您可以使用dict.setdefault作为'未知'或'0'(根据适合您的情况)将评级的默认值设置为

# set value of 'rating' as 'unknown' if 'rating' key is not present
movie.setdefault('rating', 'unknown')  

# then do format as:
"{title} => {rating}".format(**movie)

有关详情,请查看:Use cases for the setdefault dict method