TypeError:列表索引必须是整数,而不是unicode-Django python

2024-04-25 23:43:21 发布

您现在位置:Python中文网/ 问答频道 /正文

comment_json = urllib2.urlopen("https://graph.facebook.com/comments/?ids=http://www.places4two.de/location/"+locname+"/"+str(lid)+"/")
comment_dict = json.loads(comment_json.read())

如果我打印comment_dict,我将以这种形式获取dict:

{u'http://www.places4two.de/location/date-in-caroussel/2406/': 
{u'comments': 
   {u'paging': 
     {u'cursors': {u'after': u'MQ==', u'before': u'Mg=='}}, 
     u'data': [
        {u'from': {u'name': u'John Purlore', u'id': u'100005454794537'}, 
        u'like_count': 0, 
        u'can_remove': False, 
        u'created_time': u'2013-10-30T09:02:51+0000', 
        u'message': u'Essen ist richtig lecker\n', 
        u'id': u'573597026010502_13875759', 
        u'user_likes': False},
               ]
     }
    }
   }

现在我只想检查data是否有一些值:

if comment_dict['http://www.places4two.de/location/'+locname+'/'+str(lid)+'/']['comments']['data']:

但在这一行,我得到了一个错误:

TypeError: list indices must be integers, not unicode

我做错什么了?locname是locationname,str(lid)是位置id的字符串版本-因此它们是变量。

是不是因为str()


Tags: idjsonfalsehttpdatawwwcommentde
2条回答

这是因为数据返回一个对象列表,而您可能像字典一样访问它。

试试这个:

data = comment_dict['http://www.places4two.de/location/'+locname+'/'+str(lid)+'/']['comments']['data']
if len(data) > 0 and data[0].get("like_count"):
     # code for when like_count is greater than 0

使用.get()而不是[]

url = 'http://www.places4two.de/location/'+locname+'/'+str(lid)+'/'
if comment_dict.get(url).get('comments').get('data'):
     #my code.

要安全地执行此操作(不要遇到NoneType has no attribute问题),还可以执行以下操作:

url = 'http://www.places4two.de/location/'+locname+'/'+str(lid)+'/'
if comment_dict.get(url, {}).get('comments', {}).get('data', None):
     #my code.

相关问题 更多 >