General Query : Guided Project

Screen Link:

My Code: <
avg_by_hour =
for row in comments_by_hour:
hour = row[0]
avg_by_hour.append([hour, (comments_by_hour[hour] / counts_by_hour[hour])])

Replace this line with your code

What I expected to happen: Can anyone help me on above code? I expected to get the average but it is giving me below error.

What actually happened: It gave below error.

KeyErrorTraceback (most recent call last)
in ()
2 for row in comments_by_hour:
3 hour = row[0]
----> 4 avg_by_hour.append([hour, (comments_by_hour[hour] / counts_by_hour[hour])])
5 print(avg_by_hour)

KeyError: ‘1’

Replace this line with the output/error
1 Like

Hello @deodattatijare, comments_by_hour is a dictionary. This you created in the previous screen. The keys of this dictionary is the hour.

  • comments_by_hour: contains the corresponding number of comments ask posts created at each hour received.

Iterating this dictionary comments_by_hour, you’ll be iterating the dictionary key which is the hour. Therefore there is no need of hour=row[0]. Actually every key is the hour since the key are hours.

avg_by_hour = []
for hour in comments_by_hour:
    avg_by_hour.append([hour, comments_by_hour[hour]/counts_by_hour[hour]])
1 Like

Hi, your suggested code worked for me. But am still little confuse on hour as a keys of this dictionary as i am not able to visualize it. Is it like, for that comments_by_hour & counts_by_hour dictionary, we have collectively given name ‘hour’ after extracting it hours from date & time?
I did not realize it during going through course & even previous code for which i just followed the steps.

1 Like

Have a look at comments_by_hour dictionary

  • comments_by_hour : contains the corresponding number of comments ask posts created at each hour received.
    Based on how you created it, the key in this dictionary is the hour and the responding value is the number of comments created at that hour.

I did this, but it gives me error called “Dict is unhashable”.

Ow, It’s okay now, But dicts are not supposed to give results in order, right?
How are you getting these results in an ordered way?