我得到一个错误'list' object has no attribute 'get'
。通常,效果很好
weather_1D_ago = data['city']['weather']['daily'][0]['actual']['fmt']
weather_2D_ago = data['city']['weather']['daily'][1]['actual']['fmt']
'city': {'weather': {'daily': [{'actual': {'fmt': '1.2',
'raw': 1.2},
'date': '1D_ago',
'estimate': {'fmt': '1.3',
'raw': 1.3}},
{'actual': {'fmt': '2.2',
'raw': 2.2},
'date': '2D_ago',
'estimate': {'fmt': '2.3',
'raw': 2.3}},,
直到路径丢失,如下所示:
'city': {'weather': {'daily': []},
更新:我尝试使用.get()
来获取数据,如果缺少值,则使其返回为None
。你知道吗
weather_1D_ago = data['city']['weather'].get('daily', {})[0].get('actual', {}).get('fmt', {})
weather_2D_ago = data['city']['weather'].get('daily', {})[1].get('actual', {}).get('fmt', {})
但我刚得到一个错误list index out of range
我应该避免使用try-except
块,因为当引用weather_1D_ago
时,它会混淆我的其他代码,并且会生成另一个错误:local variable 'weather_1D_ago' referenced before assignment
那么,即使路径无效,如何让它使用.get()
返回None
?谢谢!你知道吗
相关问题 更多 >
编程相关推荐