【问题标题】:How do I access an element in a list item within a key of a dict?如何访问字典键内的列表项中的元素?
【发布时间】:2019-05-30 11:54:29
【问题描述】:

我目前有一个输出各种天气数据的 JSON 文件。我可以在一定程度上细化我想要的信息,但需要进一步细化但无法做到。

我尝试根据位置选择它,例如 [1],我还尝试根据键访问数据,例如['weather'] 但我只能在 Python 抛出错误之前对其进行如此多的改进。

{'coord': {'lon': -1.98, 'lat': 50.72}, 'weather': [{'id': 803, 'main': 
'Clouds', 'description': 'broken clouds', 'icon': '04d'}], 'base': 
'stations', 'main': {'temp': 293.6, 'pressure': 1022, 'humidity': 64, 
'temp_min': 292.15, 'temp_max': 294.82}, 'visibility': 10000, 'wind': 
{'speed': 5.1, 'deg': 230}, 'clouds': {'all': 75}, 'dt': 1559214671, 
'sys': {'type': 1, 'id': 1401, 'message': 0.0072, 'country': 'GB', 
'sunrise': 1559188945, 'sunset': 1559246925}, 'timezone': 3600, 'id': 
2640101, 'name': 'Poole', 'cod': 200}

上面的代码是我必须使用的 JSON 文件,我想提炼和提取例如 'weather' 中的 'main' 值,所以我想提取字符串 'Clouds' 但我已经尝试过像 dict['weather]['main'] 但它只是抛出一个错误。

寻求一些建议:D

【问题讨论】:

  • 预期输出是什么?你能把它添加到问题中

标签: python json python-3.x


【解决方案1】:

weather 的值是一个列表,因此您需要 dict['weather'][0]['main']

另外,我建议不要调用特定的字典dict,因为它隐藏了内置的dict 函数。

【讨论】:

  • 该死的,我有时讨厌解决方案多么简单......我无法相信我尝试过的一切都不是解决方案之一。非常感谢!
猜你喜欢
  • 2015-07-05
  • 2022-11-04
  • 2022-10-04
  • 1970-01-01
  • 2023-04-06
  • 2021-07-27
  • 1970-01-01
  • 2019-02-13
  • 1970-01-01
相关资源
最近更新 更多