for item in r.get_iterator():
if 'retweeted_status' in item:
print('aa')
else:
id_twitty = item['id']
count_ret = item['retweet_count']
if item['id']
throws a KeyError
exception the execution terminates.
How to make the for
loop continue its execution after the exception?
You can try and catch the KeyError
exception that gets raised and then discard it:
for item in r.get_iterator():
if 'retweeted_status' in item:
print('aa')
else:
try:
id_twitty = item['id']
count_ret = item['retweet_count']
except KeyError:
pass
Alternatively to EAFP
style, you can apply LBYL
and use continue
if id
not found in item
:
for item in r.get_iterator():
if 'retweeted_status' in item:
print('aa')
elif 'id' not in item:
continue
else:
id_twitty = item['id']
count_ret = item['retweet_count']
You could either check first if item['id']
exists:
for item in r.get_iterator():
if 'retweeted_status' in item:
print('aa')
else:
if 'id' in item:
id_twitty = item['id']
count_ret = item['retweet_count']
Or use None
if it doesn't exist:
for item in r.get_iterator():
if 'retweeted_status' in item:
print('aa')
else:
id_twitty = item.get('id')
count_ret = item['retweet_count']
Or use some other default value if it doesn't exist:
default_id = 0
for item in r.get_iterator():
if 'retweeted_status' in item:
print('aa')
else:
id_twitty = item.get('id', default_id)
count_ret = item['retweet_count']
for item in r.get_iterator():
if 'retweeted_status' in item:
print('aa')
else:
id_twitty = item.get('id', None)
count_ret = item.get('retweet_count', None)
if not id_twitty or not count_ret:
print "could not retrieve id or count"
# handle error here
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.