Search code examples
pythonloopsdictionary

Why is looping over a dictionary (made form a json) leading to an error?


I am trying to learn python. In this context, I get a json, and get a specific value. However, I get the following error:

string indices must be integers, not "str"."

for my last line of code:

print(dollar["rate_float"])

I have seen other questions on the topic, such as this one, but I am not able to apply it or really understand it.

My code is as follows:

import sys
import requests
import json

if len(sys.argv) != 2:
    print("Missing command-line argument")

# Check if the user is giving a parameter after the program name

elif sys.argv[1].isalpha():
    print("Command-line argument is not a number")

# Check if the user is giving numbers

else:
    response = requests.get("https://api.coindesk.com/v1/bpi/currentprice.json")

# Get a json from coindesk

    data_store = response.json()

# Store the json in the variable "data_store"

    for dollar in data_store["bpi"]:

# Loop over the dictionary to pick the price in dollar
        
        print(dollar["rate_float"])

After adapting the code as follows, based on the comments, I get another error: "name "bpi" is not defined".

# Store the json in the variable "data_store"

    for dollar in data_store[bpi.values()]:

# Loop over the dictionary to pick the price in dollar

        print(dollar[rate_float.values()])

The Json is as follows:

{
  "time": {
    "updated": "Feb 27, 2024 20:16:10 UTC",
    "updatedISO": "2024-02-27T20:16:10+00:00",
    "updateduk": "Feb 27, 2024 at 20:16 GMT"
  },
  "disclaimer": "This data was produced from the CoinDesk Bitcoin Price Index (USD). Non-USD currency data converted using hourly conversion rate from openexchangerates.org",
  "chartName": "Bitcoin",
  "bpi": {
    "USD": {
      "code": "USD",
      "symbol": "$",
      "rate": "57,197.495",
      "description": "United States Dollar",
      "rate_float": 57197.4947
    },
    "GBP": {
      "code": "GBP",
      "symbol": "£",
      "rate": "45,108.976",
      "description": "British Pound Sterling",
      "rate_float": 45108.9758
    },
    "EUR": {
      "code": "EUR",
      "symbol": "€",
      "rate": "52,744.155",
      "description": "Euro",
      "rate_float": 52744.1549
    }
  }
}

Solution

  • When you are looping through the dictionary the values passed into dollar are the keys of the dictionary not the values. Instead you want to use data_store["bpi"].values() since this will loop through the values which in your case are dictionarie, then you can use dollar["rate_float"].

    The code would be:

    import sys
    import requests
    import json
    
    if len(sys.argv) != 2:
        print("Missing command-line argument")
    
    # Check if the user is giving a parameter after the program name
    
    elif sys.argv[1].isalpha():
        print("Comand-line argument is not a number")
    
    # Check if the user is giving numbers
    
    else:
        response = requests.get("https://api.coindesk.com/v1/bpi/currentprice.json")
    
    # Get a json from coindesk
    
        data_store = response.json()
    
    # Store the json in the variable "data_store"
    
        for dollar in data_store["bpi"].values():
    
    # Loop over the dictionary to pick the price in dollar
            
            print(dollar["rate_float"])