修复dict理解的错误

时间:2015-09-14 20:39:32

标签: python

我有以下模式:

episodes = {key: value for key, value in 
                  item_data['seasons'][season_id]['episodes'].items() 
              if (item_data['seasons'][season_id].get('episodes') and key.isdigit())}

不幸的是,有时'episodes'将为null,从而导致以下错误:

KeyError: 'episodes'

修复上述内容的优雅方法是什么?我目前的解决方案如下:

episodes = {key: value for key, value in item_data['seasons'][season_id].get('episodes')
            if item_data['seasons'][season_id].get('episodes')}
episodes = {key: value for key, value in item_data['seasons'][season_id]['episodes'].items()
            if key.isdigit()}

1 个答案:

答案 0 :(得分:1)

episodes = {
    key: value for
    key, value in 
    item_data['seasons'][season_id].get('episodes', {}).items() 
    if key.isdigit()
}

请注意,if过滤器的第一部分并非必要,因为{}.items()没有密钥:)