"TypeError: 'int' object is not subscriptable" on Guided Project: Exploring Hacker News

Screen Link:


My Code:

import datetime as dt
result_list = []

for row in ask_post:
    comments = int(row[4])

counts_by_hour = {}
comments_by_hour = {}

for row in result_list:
    date =  row[1]
    hour = dt.datetime.strptime(date, '%H')
    if hour in counts_by_hour:
        counts_by_hour[hour] += 1
        counts_by_hour[hour] = 1

What I expected to happen:
In this guided project, I intended on creating a dictionary that took the frequency of the hours that meetings occured.

What actually happened:

TypeErrorTraceback (most recent call last)
<ipython-input-6-220b7de49f52> in <module>()
     12 for row in result_list:
---> 13     date =  str(row[1])
     14     hour = dt.datetime.strptime(date, '%H')
     15     if hour in counts_by_hour:

TypeError: 'int' object is not subscriptable

I would also like to know why this error shows up? So I can determine the solution when I run into this problem in the future

Hey @markrune636. The error shows up because of the way result_list was created, so it ends up looking like this:

[6, '8/16/2016 9:55',  29,  '11/22/2015 13:43',  1,  '5/2/2016 10:14',  3,  '8/2/2016 14:20', ...]

When it gets to the loop, for row in result_list is going to take each element as row. In the first iteration, that means row = 6. When it tries to execute date = row[1], it can’t, because it’s just an integer, and so it throws up the error.

Others had a similar issue talked about in this post, but they had a different error than you because they swapped the number of comments and date in result list. It’s still the same problem though, so have a read on that post since there’s a hint there on how to resolve the problem.

I hope that helps!

(And just a heads up: you’re going to hit another snag once that part is resolved, related to the datetime.strptime() piece of the code. I’ll let you work that out, but if you get stuck, feel free to post in this topic again and the community will help you get it sorted!)