TypeError: list indices must be integers, not unicode - django python
11,657
Solution 1
Use .get()
instead of []
url = 'http://www.places4two.de/location/'+locname+'/'+str(lid)+'/'
if comment_dict.get(url).get('comments').get('data'):
#my code.
To do this safely (Not run into NoneType has no attribute
issues ), you could also do:
url = 'http://www.places4two.de/location/'+locname+'/'+str(lid)+'/'
if comment_dict.get(url, {}).get('comments', {}).get('data', None):
#my code.
Solution 2
This is because data returns a list of objects, while you're likely accessing it like a dictionary.
Try this:
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
Author by
doniyor
Python Developer, Django Developer, Fullstack. Ideas. World. Changes. Trace.
Updated on June 05, 2022Comments
-
doniyor almost 2 years
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())
if I print
comment_dict
, i am getting dict in this form this:{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}, ] } } }
and now I just want to check if
data
has some value or not:if comment_dict['http://www.places4two.de/location/'+locname+'/'+str(lid)+'/']['comments']['data']:
but in this line, i am getting the error:
TypeError: list indices must be integers, not unicode
what am i doing wrong?
locname
is locationname andstr(lid)
is string version of location_id - so they are variables.isnot it because of
str()
?-
Steve Jessop over 10 yearsI don't believe that you have shown the faulty case: ideone.com/JTsusD. More likely you've hit a case where one of
comment_dict
orcomment_dict[url]
orcomment_dict[url]['comments']
is an empty list[]
rather than a dictionary, if that's permitted by the facebook API you're using. -
oleg over 10 yearscan You find out which of
[]
return this ?
-
-
VooDooNOFX over 10 years
.get()
returnsNone
by default. The final.get('data', None)
call could be shortened to.get('data')
. -
oleg over 10 yearsIn this case
KeyError
should be raised notTypeError
-
doniyor over 10 yearsso i dont need
urllib2
even? -
karthikr over 10 yearsYou do need
urllib2
- This is just the dictionary parsing logic. -
karthikr over 10 years@VooDooNOFX Agreed, but I wanted to just show it explicitly so that the OP can choose to do
.get('data', [])
-
doniyor over 10 yearsyeah, thanks, that was stupid question. i deleted it.