python - 具有多个键的 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/"
]
},
解决方案
要遍历您需要调用.keys()
字典的键,但您不需要这样做。只需将键与字典一起使用,如下所示。
for dict_ in json_response:
if float(dict_['rt_score']) > 90:
title = dict_['title']
print(title)
推荐阅读
- javascript - 安装后我的 React Native 应用程序大小太大
- python - pygame.mixer.music 播放音频很好,但 pygame.mixer.Sound 给出错误“无法打开文件”
- asp.net-mvc - ASP。使用数据库中的资源数据进行网络核心本地化
- git - 如何让 git 忽略已删除但似乎可以看到的文件?
- python - 匹配不同数据帧的两个相同列中的值以获得另一列的对应值
- powershell - Hyper-V Powershell - 将冒号添加到 MAC 地址
- php - Laravel - 模型字段返回空值
- select - “选择 c”的含义。在 SQL 中
- laravel - Laravel lighthouse / graphQL - 在嵌套查询中调用时将模型列表限制为用户可以访问的模型
- c++ - std::chrono time_t 转换溢出?