Reputation: 269
I got an error of 'list' object has no attribute 'get'
. Usually, it worked fine,
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}},,
Until the path was missing, as shown below:
'city': {'weather': {'daily': []},
Update: I tried to use .get()
to achieve the data, and make it return as None
if the value is missing.
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', {})
But I just got an error of list index out of range
I'd avoid using try-except
blocks because it will mix up my other codes when referred to weather_1D_ago
and another error will generate: local variable 'weather_1D_ago' referenced before assignment
So, how would you make it return None
using .get()
even if the path is not valid? Thanks!
Upvotes: 0
Views: 92
Reputation: 760
def safe_list_get(l, i):
if l and i < len(l):
return l[i]
return {}
weather_1D_ago = safe_list_get(data['city']['weather'].get('daily', []),0).get('actual', {}).get('fmt', {})
weather_2D_ago = safe_list_get(data['city']['weather'].get('daily', []),1).get('actual', {}).get('fmt', {})
Upvotes: 1