Guided Project Exploring Hacker News Posts - Key Error: 2

Hey guys!

As I was writing the guided project: Exploring Hacker News Posts, I met with the following error, I tried to debug it, but I don’t know what this error is about, so it didn’t work, if anyone knows how to correct it, please let me know!

Screen Link:

My Code:

result_list =[]
for row in ask_post:
    created_at = row[6]
    comments = int(row[4])
    result_list.append([created_at, comments])
print(result_list[:3])

date_format = "%m/%d/%Y %H:%M"
counts_by_hour = {}
comments_by_hour = {}
for row in result_list:
    c = row[1]
    date = row[0]
    date = dt.datetime.strptime(date, date_format)
    hour = date.hour
    if hour in counts_by_hour:
        counts_by_hour[hour] += 1
        comments_by_hour[hour] += c
    elif hour not in counts_by_hour:
        counts_by_hour[hour] = 1
        comments_by_hour[hour] += c

print(counts_by_hour)
print(comments_by_hour)

What I expected to happen:

{‘02’: 2996,
‘01’: 2089,
‘22’: 3372,
‘21’: 4500,
‘19’: 3954,
‘17’: 5547,
‘15’: 18525,
‘14’: 4972,
‘13’: 7245,
‘11’: 2797,
‘10’: 3013,
‘09’: 1477,
‘07’: 1585,
‘03’: 2154,
‘23’: 2297,
‘20’: 4462,
‘16’: 4466,
‘08’: 2362,
‘00’: 2277,
‘18’: 4877,
‘12’: 4234,
‘04’: 2360,
‘06’: 1587,
‘05’: 1838}

What actually happened:

KeyError                                  Traceback (most recent call last)
<ipython-input-37-f93c029790dc> in <module>
     12     elif hour not in counts_by_hour:
     13         counts_by_hour[hour] = 1
---> 14         comments_by_hour[hour] += c
     15 print(counts_by_hour)
     16 print(comments_by_hour)

KeyError: 2

Ps: when I run the code just for “counts_by_hour”, it runs smooth

Hello @luiza.licariao,

The bug is here

It should be comments_by_hour[hour] = c

If hour is not in counts_by_hour, you cannot add c to it.

You can also use the else statement here instead since the two conditions are mutually exclusive

else:
    counts_by_hour[hour] = 1
    comments_by_hour[hour] = c
1 Like

Wow, I can’t believe I didn’t notice it haha
Thanks a lot, @doyinsolamiolaoye!