Search code examples
pythonfinancebitcoinalpha-vantage

Print only a part of the answer on python


I use an API to have stock or crypto prices. The code I have to execute is this one :

resp = requests.get('https://www.alphavantage.co/query', params={
    'function': 'CURRENCY_EXCHANGE_RATE',
    'from_currency': 'BTC', 
    'to_currency': 'EUR',
    'apikey': AV_API_KEY
})
resp

resp.json()

It gave me this answer :

{'Realtime Currency Exchange Rate': {'1. From_Currency Code': 'BTC',
  '2. From_Currency Name': 'Bitcoin',
  '3. To_Currency Code': 'EUR',
  '4. To_Currency Name': 'Euro',
  '5. Exchange Rate': '14161.84281800',
  '6. Last Refreshed': '2020-11-28 09:32:04',
  '7. Time Zone': 'UTC',
  '8. Bid Price': '14161.61726000',
  '9. Ask Price': '14161.62561400'}}

But my purpose is to only have the Exchange Rate so to only print 14161.84281800 and not the other infos.

I tried this :

print(resp.json('5. Exchange Rate')

But I have a SyntaxError: unexpected EOF while parsing

Is it possible to print only the Exchange Rate or do I have to first execute all the infos and then isolate Exchange Rate to use it for other code?


Solution

  • try this

    a={'Realtime Currency Exchange Rate': {'1. From_Currency Code': 'BTC',
      '2. From_Currency Name': 'Bitcoin',
      '3. To_Currency Code': 'EUR',
      '4. To_Currency Name': 'Euro',
      '5. Exchange Rate': '14161.84281800',
      '6. Last Refreshed': '2020-11-28 09:32:04',
      '7. Time Zone': 'UTC',
      '8. Bid Price': '14161.61726000',
      '9. Ask Price': '14161.62561400'}}
    k=a.get('Realtime Currency Exchange Rate')
    print(k.get('5. Exchange Rate'))
    

    first store the json data in a variable then use this program

    or
    

    store json data in "a" variable then use this print

    print(a.get('Realtime Currency Exchange Rate').get('5. Exchange Rate'))