python - Coinmarketcap 数据嵌套字典
问题描述
嗨,我仍处于学习 python 的初级阶段。我正在尝试使用他们的 api 系统从 Coinmarketcap.com 提取数据。我可以使用一本大字典获得输出,但似乎无法弄清楚如何提取特定数据。我想只收到'价格':和'最后更新'。
我尝试引用 .loads 并将数据切片到列表中。我也尝试在字典中建立索引,但输出中的嵌套字典让我难以理解。我看过很多 youtube 教程并在 Google 上寻求帮助,但无法找到解决方案。任何帮助将不胜感激!
import requests
import json
url ='https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest'
api_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx'
headers = {'Accepts': 'application/json', 'X-CMC_PRO_API_KEY': api_key}
parameters = {'symbol': 'ADA'}
response = requests.get(url, headers = headers, params = parameters)
data = response.json()
data_str = json.dumps(data, indent = 2)
print(data_str)
这是字典的输出:
{“状态”:{“时间戳”:“2019-07-17T20:54:40.829Z”,“error_code”:0,“error_message”:null,“elapsed”:7,“credit_count”:1},“数据": {"ADA": {"id": 2010, "name": "Cardano", "symbol": "ADA", "slug": "cardano", "num_market_pairs": 90, "date_added": "2017 -10-01T00:00:00.000Z", "tags": ["mineable"], "max_supply": 45000000000, "circulating_supply": 25927070538, "total_supply": 31112483745, "platform": null, "cmc_rank": 12 , "last_updated": "2019-07-17T20:54:04.000Z", "quote": {"USD": {"price": 0.056165857414, "volume_24h": 102375843。427606,“percent_change_1h”:-0.816068,“percent_change_24h”:5.42849,“percent_change_7d”:-21.8139,“market_cap”:1456216147.0000284,“last_updated”:“2019-07-17T20:54:04.0000Z”
解决方案
在 Python 中,您只需执行以下操作即可访问字典的值
value = dict[key]
在您的情况下,您有一个嵌套的 JSON。您可以通过链接键来访问这些值。
你的 JSON 看起来像
{
"status": {
"timestamp": "2019-07-17T20:54:40.829Z",
"error_code": 0,
"error_message": null,
"elapsed": 7,
"credit_count": 1
},
"data": {
"ADA": {
"id": 2010,
"name": "Cardano",
"symbol": "ADA",
"slug": "cardano",
"num_market_pairs": 90,
"date_added": "2017-10-01T00:00:00.000Z",
"tags": ["mineable"],
"max_supply": 45000000000,
"circulating_supply": 25927070538,
"total_supply": 31112483745,
"platform": null,
"cmc_rank": 12,
"last_updated": "2019-07-17T20:54:04.000Z",
"quote": {
"USD": {
"price": 0.056165857414,
"volume_24h": 102375843.427606,
"percent_change_1h": -0.816068,
"percent_change_24h": 5.42849,
"percent_change_7d": -21.8139,
"market_cap": 1456216147.0000284,
"last_updated": "2019-07-17T20:54:04.000Z"
}
}
}
}
}
您可以访问价格
price = data['data']['ADA']['quote']['USD']['price']
希望能帮助到你
推荐阅读
- c# - 如何在 alpine 3.8 中安装 pythonnet
- html - 在 Bootstrap 中,如何使步进器全宽
- android - Custom notification sound is not working at NotificationChannel for android P
- mysql - Mysql连接太多:Django sqlAlchemy
- javascript - Vue js 动态导入组件
- jquery - 如何将第三方 JS 库集成到我的 React JS 应用程序中
- wpf - ComboBox 未显示 SelectedItem 绑定到的值
- javascript - 如何在单键值对数组中获取嵌套的 json 对象值
- javascript - jquery toggle 在表 tr 上无法正常工作
- xml - 使用 Bash 从 XML 属性中获取注释标记