Need help understanding this code : Guided Project- Profitable Apps

I understand creating an empty dictionary, creating the variables: name and n_reviews but Im not fully understanding the conditional statements. The goal of this tutorial is to create a dictionary where each key stores a unique app name and the corresponding dictionary value is highest number of reviews of that app. Thanks.

reviews_max = {}

for app in android:
name = app[0]
n_reviews = float(app[3])

if name in reviews_max and reviews_max[name] < n_reviews:
    reviews_max[name] = n_reviews
    
elif name not in reviews_max:
    reviews_max[name] = n_reviews
# If the app is already in our dictionary, we want to update
# the highest number of reviews if the current value of n_reviews
# is higher than the previous one.
if name in reviews_max and reviews_max[name] < n_reviews: 
    reviews_max[name] = n_reviews
# If the app isn't already in the dictionary, we add it and assign
# the current value of n_reviews as the highest number.
elif name not in reviews_max:
    reviews_max[name] = n_reviews

If the app is already in the dictionary but the current value of n_reviews is not the highest seen so far, nothing happens.

1 Like

Hi Choudhary, the simplest way I understood it is:

  1. We create an empty dictionary that we are going to populate with app names and the corresponding number of reviews.

  2. We iterate over each app in our android dataset and for each iteration:

    • Identify the app name

    • identify the number of reviews for that app ( as a float)

    • check if the name of the app exists as a key in our dictionary
      if name in reviews_max

    • check if the number of reviews currently associated with the app name in our dictionary is less than the number of reviews.
      reviews_max[name] < n_reviews:

    • As we iterate through the android dataset and come across a different number of reviews for the same app name we will check to see if it is higher than what we have already stored in the dictionary and if this true we will update our key with this new higher value.
      if name in reviews_max and reviews_max[name] < n_reviews: reviews_max[name] = n_reviews

    • But if we do find another instance of the same app name with a lower number of reviews we will ignore it.

    • However, if the name of the app is not in our dictionary then we add it to our dictionary with its corresponding number of reviews.
      elif name not in reviews_max:
      reviews_max[name] = n_reviews

Hope this helps. I’m learning as well and know how complicated things can get. I try to run through it in pseudo-code to help me grasp what I’m doing.

3 Likes

Hi, @williamkaen your explanation on this topic is just what I needed to understand this code. Good job you did with the explanation, so apt and simplified.

Regards,
Olubaji

2 Likes

@olubaji22. I’gald I was able to help. Happy coding.