无法从Api动态访问具有重复值的字典-Python for Binance

时间:2018-06-26 16:11:50

标签: python api dictionary python-requests

我正在尝试格式化此Api https://www.binance.com/api/v1/ticker/allBookTickers

这是Api的缩写版本

  

[{“ symbol”:“ ETHBTC”,“ bidPrice”:“ 0.07200500”,“ bidQty”:“ 0.67800000”,“ askPrice”:“ 0.07203200”,“ askQty”:“ 7.19200000”},{“ symbol” :“ LTCBTC”,“ bidPrice”:“ 0.01281100”,“ bidQty”:“ 10.90000000”,“ askPrice”:“ 0.01282500”,“ askQty”:“ 1.01000000”}]

每个字典都保存为列表中的索引,我的问题是每个字典都以“符号”开头,而不是以“ ETHBTC”之类的名字开头

我可以调用索引号,但是因为它们在api中有数百个字典,所以我需要找到一种能够键入“ ETHBTC”来调用该字典的方法?

这是理想世界中的样子,但我不知道如何实现这一目标,将不胜感激吗?

> data = requests.get('https://www.binance.com/api/v1/ticker/allBookTickers')
> data = data.json() 
> ltc = data['LTCBTC']

1 个答案:

答案 0 :(得分:0)

使用以下代码:-

import requests

#fetched data from url using requests
data = requests.get('https://www.binance.com/api/v1/ticker/allBookTickers')

# creating json object from response
dataJson = data.json() 

# creating dictionary from json object using symbol value as key
dataDictionary = {d['symbol'] : d for d in dataJson}

# accessing dictionary object using symbol value
ltc = dataDictionary['LTCBTC']

print ltc

# now you can use ltc values by given keys as, and so on for other values
print ltc['askPrice']

在这段代码中,我们根据返回的响应创建了python字典。