2013-10-30 89 views
2
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

,我在這種形式這讓字典:類型錯誤: - 列表索引必須是整數,不是Unicode Django的蟒蛇

{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)是location_id的字符串版本 - 所以它們是變量。

是不是因爲str()

+1

我不相信你已經出故障的情況下:http://ideone.com/JTsusD。更有可能的是,你已經觸及'comment_dict'或'comment_dict [url]'或'comment_dict [url] ['comments']'是一個空列表[]'而不是字典,如果這是允許的您正在使用的Facebook API。 –

+0

你能找出哪個'[]'返回這個? – oleg

回答

4

使用.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. 
+0

'.get()'默認返回'None'。最後的.get('data',None)'調用可以縮短爲'.get('data')'。 – VooDooNOFX

+0

在這種情況下'KeyError'應該不會出現'TypeError' – oleg

+0

,所以我不需要''urllib2''甚至? – doniyor

3

這是因爲數據返回的對象列表,而你可能像字典一樣訪問它。

試試這個:

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 
相關問題