Print only a part of the answer on python

100 views Asked by At

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?

4

There are 4 answers

4
sourab maity On BEST ANSWER

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'))
1
scsanty On

This should work.

print(resp.json()['Realtime Currency Exchange Rate']['5. Exchange Rate'])

The error you see is because, you didn't end the print statement properly. There is supposed to be two ) brackets.

But even so you'll get an error, because json is like a dictionary within dictionary and so on.

So if you're referencing something from the inner set, you have to follow down the keys.

1
Stu On

The call to resp.json() will result in a dictionary. You can access the data like so

exchange = resp.json()
print(exchange['Realtime Currency Exchange Rate']['5. Exchange Rate'])

Use a try/except to catch any KeyError errors that may occur.

try:
    print(exchange['Realtime Currency Exchange Rate']['5. Exchange Rate'])
except KeyError:
   print('Could not fetch exchange rate.')
0
chashikajw On

Simpleset answer. print(resp.json()['Realtime Currency Exchange Rate']['5. Exchange Rate'])

you can get all the values using for loop

dataArr = resp.json()['Realtime Currency Exchange Rate']
for valuekey in dataArr:
   print(valuekey, dataArr[valuekey])