Kushal Agarwal Kushal Agarwal - 1 year ago 83
Python Question

Tweets in Python

def twitter_search(twitter_api,q,max_results=200,**kw):
search_results = twitter_api.search.tweets(q=q,count=100,**kw)
statuses = search_results['statuses']
for _ in range(10):
next_results = search_results['search_metadata']['next_results']
except KeyError, e:
kwargs = dict([ kv.split('=')
for kv in next_results[1:].split("&") ])
search_results = twitter_api.search.tweets(**kwargs)
statuses += search_results['statuses']
if len(statuses) > max_results:
return statuses

results = twitter_search(twitter_api,q,max_results=10)
print json.dumps(results[0], indent =1)

The last line is returning an error that
'NoneType' object has no attribute __getitem__

Answer Source

You have two issues here:

  1. The return statement is inside the for loop, and might not be reached if the loop hits one of the break statements first. If it is reached, it will return earlier than you want, without running the rest of the loop iterations.

  2. You are assuming results will have at least one element (results[0]). If results is an empty list, this will fail with an IndexError.


  1. Move the return statement outside of the for loop (dedent one level).

  2. Check if results: before indexing into it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download