How would I get past this assertion test in Python for trying to find the sum of all the number of views? Below is the dictionary I am given, and then below that is assertion test I am trying to pass. I have to create a function that returns something that passes the assertion.
video_reviews = [
{
"name": "Cats doing nothing",
"number_of_views": 450743,
"reviews": [
{"name": "Jeb", "review": 5},
{"name": "Samantha", "review": 2},
{"name": "Crystal", "review": 3},
]
},
{
"name": "All Fail",
"number_of_views": 1239734,
"reviews": [
{"name": "Crystal", "review": 5},
{"name": "Frank", "review": 3},
{"name": "Jeb", "review": 3},
]
},
{
"name": "Runaway Nintendo",
"number_of_views": 48343,
"reviews": [
{"name": "Samantha", "review": 4},
{"name": "Bill", "review": 3},
{"name": "Sarah", "review": 4},
]
},
]
assert total_by_video(video_reviews, "Runaway Nintendo") == 48343
assert total_by_video(video_reviews, "All Fail") == 1239734
assert total_by_video(video_reviews, "Critters") == 0
video_reviews
is a list of dictionaries. For a single dictionary d
you can get the number of views like this: number_of_views=d["number_of_views"]
With that knowledge you can use either a for-loop or list-comprehension to create a list that contains only the numbers.
number_of_views_list = [450743, 1239734, 48343]
Now all you have to do is sum up this list. This can be done by a for-loop as well, or you could make use of the sum
function.
Your function would probably look somewhat like this:
def sum_of_views(reviews):
# TODO create number_of_views_list
# TODO sum up number_if_views_list
return result
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.