0

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?

2
  • token['bitcoin']['usd'] try this Commented Apr 11, 2021 at 4:01
  • @mhhabib I updated to print(token['bitcoin']['usd']) but I get KeyError: 'bitcoin' Commented Apr 11, 2021 at 4:03

2 Answers 2

1

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']) 
Sign up to request clarification or add additional context in comments.

Comments

0

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']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.