Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I access something within a dictionary, thats within a list, thats within a dictionary?

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):

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  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!

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading