首页 > 解决方案 > 具有多个键的 Python 字典列表

问题描述

我对 Python 还很陌生,所以对于我的帖子中发现的任何错误,我深表歉意。我最近一直在使用 Python 使用 API,遇到了一个 API,它通过提供 API 的各个工作室的电影词典列表来响应我的请求(不确定它是否是 JSON 词典列表)我正在尝试创建一个 for 循环以获得大于 90 的烂番茄分数,但我也想在 for 循环中获取电影的相应标题。我已经尝试添加if key == 'rt_score' and 'title',但我不知道这是否是正确的方法以及它是否会引导我找到正确的解决方案。这是我的代码:

import requests
import json

response = requests.get("https://ghibliapi.herokuapp.com/films")

print(response.status_code)
json_response = response.json()

for dicti in json_response:
    for key in dicti:
        if key == 'rt_score':
            rt_score = int(dicti[key])
            if rt_score > 90:
                print(str(key) + ': ' + str(rt_score))

这是字典的 JSON 列表的样子:

[
   {
      "description": "The orphan Sheeta inherited a mysterious crystal that links her to the mythical sky-kingdom of Laputa. With the help of resourceful Pazu and a rollicking band of sky pirates, she makes her way to the ruins of the once-great civilization. Sheeta and Pazu must outwit the evil Muska, who plans to use Laputa's science to make himself ruler of the world.",
      "director": "Hayao Miyazaki",
      "id": "2baf70d1-42bb-4437-b551-e5fed5a87abe",
      "locations": [
         "https://ghibliapi.herokuapp.com/locations/"
      ],
      "people": [
         "https://ghibliapi.herokuapp.com/people/"
      ],
      "producer": "Isao Takahata",
      "release_date": "1986",
      "rt_score": "95",
      "species": [
         "https://ghibliapi.herokuapp.com/species/af3910a6-429f-4c74-9ad5-dfe1c4aa04f2"
      ],
      "title": "Castle in the Sky",
      "url": "https://ghibliapi.herokuapp.com/films/2baf70d1-42bb-4437-b551-e5fed5a87abe",
      "vehicles": [
         "https://ghibliapi.herokuapp.com/vehicles/"
      ]
   },

标签: python

解决方案


要遍历您需要调用.keys()字典的键,但您不需要这样做。只需将键与字典一起使用,如下所示。

for dict_ in json_response:
    if float(dict_['rt_score']) > 90:
        title = dict_['title']
        print(title)

推荐阅读