Project 1 - Python for Data Analyst Question

Hi All, I am struggling with the part two of the guided project. I would really like someone to explain the working of the code:

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

I am not able to understand that how values with higher ratings are getting appended in the dictionary. My issue is not with the code as I can make it work but i am struggling to understand the concept. I would really appreciate, if someone can explain the working in simple terms.


I have explained the code below.

  1. The code reviews_max = {} creates an empty dictionary. The dictionary stores the key along with the value. So, initially the dictionary reviews_max is empty.

  2. In the for loop, the app name and number of reviews are extracted and stored in the variables name and n_reviews.

  3. Now, when the if condition is executed, the first time, the elif condition is executed (reviews_max is empty and so name not in reviews_max: is executed. (For eg: Instagram:10000 will be stored in the reviews_max dictionary)

  4. Next time, when the same app is encountered(eg. Instagram), the condition name in reviews_max is satisfied and the next condition reviews_max[name] < n_reviews is checked. The value which is already stored in the dictionary(eg. 10000) is compared with the n_reviews (reviews_max[name] < n_reviews).

  • If the condition is satisfied, it means the current n_reviews (eg. 12000) is greater than the dictionary value (eg. 10000) , and so the dictionary value is overwritten with the current value of n_reviews (eg. 12000).

  • If the condition is not satisfied, it means the current n_reviews (eg. 9000) is lesser than the dictionary value (eg. 10000), so no code will be executed and the value which is already stored in the dictionary (eg. 10000) will not be overwritten.

So every time, we iterate through an app, the no.of reviews will overwrite the dictionary value if it is greater than the value already stored in the dictionary. So at the end, the dictionary will have the ‘highest number of reviews’ stored in it.

Hope the above explanation helps you. Happy Coding.

1 Like