Below is the solution to this guided project, my challenge is, can someone please explain the logic behind this line of code -> comments_by_hour[time] += comment
Calculate the amount of ask posts created during each hour of day and the number of comments received.
import datetime as dt
result_list =
for post in ask_posts:
result_list.append(
[post[6], int(post[4])]
)
comments_by_hour = {}
counts_by_hour = {}
date_format = “%m/%d/%Y %H:%M”
for each_row in result_list:
date = each_row[0]
comment = each_row[1]
time = dt.datetime.strptime(date, date_format).strftime("%H")
if time in counts_by_hour:
comments_by_hour[time] += comment
counts_by_hour[time] += 1
else:
comments_by_hour[time] = comment
counts_by_hour[time] = 1
comments_by_hour
This is like saying comments_by_hour[time] = comments_by_hour[time]+comment
. +=
(also known as addition assignment) adds another value with the comments_by_hour[time]
's value and assigns the new value to the comments_by_hour[time]
.
It is easier to understand this logic using variables:
>>> age = 20
>>> age = age + 1
>>> print(age)
21
We can rewrite the above code using the addition assignment
>>> age = 20
>>> age += 1
>>> print(age)
21
Okay, I do understand the logic you explained, but in this case, this is making a dictionary. Here’s the link, so you can have a wholistic view of the concept I’m having issues with. My question is in the 6th cell. https://github.com/dataquestio/solutions/blob/master/Mission356Solutions.ipynb
Total number of comments at a given hour.
Okay, thank you so much. It’s now clear.
1 Like