BlueSky Trading
BlueSky Trading

Reputation: 125

Return a specific value from an API

I use this script to get crypto prices:

from pycoingecko import CoinGeckoAPI
import json

cg = CoinGeckoAPI()
response = cg.get_price(ids='bitcoin', vs_currencies='usd')
print(response)

token = response.get('bitcoin','')
print(token)

and the output returned is:

{'bitcoin': {'usd': 60302}}

{'usd': 60302}

How can I get just the value 60302 instead of the full column?

Upvotes: 0

Views: 78

Answers (2)

Croves
Croves

Reputation: 400

The response is a nested dictionary. So you have the first one, named Bitcoin and inside it you have another dictionary named usd. So this is how your data looks like:

{
    'Bitcoin': {
        'USD': '60320'
    }
}

Since you know the name of the keys, you can access these directly by typing like this: token['bitcoin']['usd']

Upvotes: 0

StevenHarvey
StevenHarvey

Reputation: 136

It's return a Dictionary, and the best way to parse a dictionary is as follows:

from pycoingecko import CoinGeckoAPI
import json

cg = CoinGeckoAPI()
response = cg.get_price(ids='bitcoin', vs_currencies='usd')
print(response) #remove this to get rid of all of the other text and just return usd

token = response.get('bitcoin','')
print(token['usd']) # Just put the name of the key 'usd' here!

If you wanted it to tell you what cryptocoin:

from pycoingecko import CoinGeckoAPI
import json

cg = CoinGeckoAPI()
response = cg.get_price(ids='bitcoin', vs_currencies='usd')


token = response.get('bitcoin','')
print("Bitcoin price: ", token['usd']) 

Upvotes: 1

Related Questions