为什么循环字典(由 json 构成)会导致错误?

问题描述 投票:0回答:1

我正在尝试学习Python。在这种情况下,我得到一个json,并得到一个特定的值。但是,我收到以下错误:“字符串索引必须是整数,而不是“str”。”我的最后一行,“

print(dollar["rate_float"])

我看过有关该主题的其他问题,例如这个one,但我无法应用它或真正理解它。

我的代码如下:

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"]:

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

根据注释修改代码如下,我收到另一个错误:“名称“bpi”未定义”。

# 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()])

Json如下:

{
  "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
    }
  }
}
python loops dictionary
1个回答
0
投票

当您循环遍历字典时,传递到 Dollar 的值是字典的键而不是值。相反,您想使用

data_store["bpi"].values()
,因为这将循环遍历您的情况下是字典的值,然后您可以使用
dollar["rate_float"]

代码为:

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"])
© www.soinside.com 2019 - 2024. All rights reserved.