【问题标题】:Pull a value from a dictionary从字典中提取一个值
【发布时间】:2017-08-08 16:38:32
【问题描述】:

每当我尝试提取温度值时都会出错。错误是:TypeError: string indices must be integers

这是我的代码:

for item in data['main']:
    tempday=item['temp']

这是我从中提取的 API:

{
"coord": {},
"weather": [],
"base": "stations",
"main": {
    "temp": 53.2,
    "pressure": 1021,
    "humidity": 71,
    "temp_min": 44.6,
    "temp_max": 57.2
},
"visibility": 16093,
}

我想获得 53.2 的“温度”值。我的代码有什么问题?

【问题讨论】:

  • 试试data['main']['temp']

标签: python json api dictionary


【解决方案1】:

您的代码假定data['main'] 的内容是dicts 的iterable,并试图获取所有dicts 中的temp

由于它只是另一个 dict,您可以删除 for 循环并简单地使用

tempday=item['main']['temp']

【讨论】:

  • 恭喜。您的答案至少比接受的答案好 -3 倍;)或者最多,我不知道正确的术语应该是什么。
【解决方案2】:

为了解释错误,通常一个 dict 迭代它的键,在这种情况下,键只是字符串。这样做:

for k in some_dict:
  # k is a string
  # some_dict[k] return the value of k in the dict

【讨论】:

    【解决方案3】:

    tempday=item['temp'] 返回键名。您需要迭代以获取所有项目的值。 data['main']

    for item in data['main']:
         data['main'][item]
    

    输出

    53.2 
    1021
    71
    44.6
    57.2
    

    只得到一件物品

    tempday=data['main']['temp']
    

    【讨论】:

    • 这不是一个正确的解决方案。它将获得所有项目:temppressurehumidity...
    猜你喜欢
    • 1970-01-01
    • 2021-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-02
    • 2013-06-09
    相关资源
    最近更新 更多