0

我可以在我的 django python shell 中使用p['cover']['source']. 我还可以使用点符号访问模板中的“源”,但是,当尝试p['cover']['source']在我的视图中访问时,我得到一个 keyError。我能够使用“封面”访问,p.get('cover','none')但我需要获得p['cover']['source'],但我不知道如何访问它。请帮忙 :-)

  views.py
  image_table = []
       for n in likes:
       link = n.facebook_id
       p = graph.get_object(str(link))
       #image = p['cover']['source'] //This returns KeyError
       #image = p['cover'][0]['source'] //This returns KeyError = 0
       image = p.get('cover','none')//This only returns the first dictionary
       image_table.append(image)
4

1 回答 1

0

有些用户可能没有封面图片,导致KeyError访问词典时出现问题。使用 try/except 块来防止错误:

try:
    image = p['cover']['source']
except KeyError:
    pass  # or other alternative for those without cover picture
于 2013-08-23T23:26:32.847 回答