使用get()

时间:2018-03-22 23:02:57

标签: python

我收到'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

那么,即使路径无效,您如何使用None返回.get()?谢谢!

1 个答案:

答案 0 :(得分:1)

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', {})