How would I access the object 'c' in a print statement?
{'symbol': 'BTCUSD', 'totalResults': 1, 'results': [{'o': 41002.26, 'h': 43361, 'l': 40875.51, 'c': 42364.13, 'v': 59454.94294, 't': 1647993599999}]}
Overall code(API KEY REMOVED BUT ISNT THE ISSUE):
command = ""
while(command != "q"):
command = input("Choose [c] for current price, [p] for previous days price, and [q] to quit.")
if(command == "c"):
coin = input("Enter currency pair: ")
crypto_data = (requests.get(f'https://api.finage.co.uk/last/crypto/{coin}?apikey=API_KEY')).json()
print(f"The current price of {coin} is {crypto_data['price']}")
if(command == "p"):
coin = input("Enter currency pair: ")
crypto_data = (requests.get(f'https://api.finage.co.uk/agg/crypto/prev-close/{coin}?apikey=API_KEY')).json()
*print(f"The previous price of {coin} is {crypto_data['results']['c']}")*
- being where I get the issue I get back a variety of codes, mostly I cant call a string and it must be a slice or integer
I have tried a range statement as well but it also brings back an error
TIA!
CodePudding user response:
The same way you would do it if they were in a dictionary first, then an array, and then a dictionary again:
crypto_data = {'symbol': 'BTCUSD', 'totalResults': 1, 'results': [{'o': 41002.26, 'h': 43361, 'l': 40875.51, 'c': 42364.13, 'v': 59454.94294, 't': 1647993599999}]}
print(crypto_data["results"][0]["c"])
This is because:
# crypto_data is a dictionary, so you can access items by their key, i.e.
crypto_data["results"]
# which returns an array: [{'o': 41002.26, 'h': 43361, 'l': 40875.51, 'c': 42364.13, 'v': 59454.94294, 't': 1647993599999}]
# so then access items in the array by their index, i.e.
crypto_data["results"][0]
# which returns a dictionary: {'o': 41002.26, 'h': 43361, 'l': 40875.51, 'c': 42364.13, 'v': 59454.94294, 't': 1647993599999}
# so then access items in the dictionary by their key again, i.e.
crypto_data["results"][0]["c"]
# which returns an integer: 42364.13
CodePudding user response:
if
myDict = {'symbol': 'BTCUSD', 'totalResults': 1, 'results': [{'o': 41002.26, 'h': 43361, 'l': 40875.51, 'c': 42364.13, 'v': 59454.94294, 't': 1647993599999}]}
then myDict["results"][0]["c"] would return 42364.1
CodePudding user response:
It's because despite you know that the dictionary is within a list, you're trying to access the dictionary as if it wasn't within a list.
This is really important: this API can return more than one dictionary in the results
list - see the totalResults
key.
The best way to get the results is to do a for
... range
loop:
for idx in range(crypto_data['totalResults']): print(crypto_data['results'][idx])