Last answered:

25 Aug 2022

Posted on:

24 Aug 2022

0

Iterating Over Dictionaries Exersize

Hello,

For the aforementioned exercise, the given solution to part one is:

for i in quantity:
    if prices[i]>=5:
        money_spent += prices[i]*quantity[i]
    else:
        money_spent = money_spent

print (money_spent)

I am wondering why exactly this solution does not work

for i in quantity:
    if i>=5:
        money_spent += prices[i]*quantity[i]
    else:
        money_spent = money_spent

print (money_spent)

1 answers ( 0 marked as helpful)
Instructor
Posted on:

25 Aug 2022

0

Hi Alan!
Thanks for reaching out.

This is because we want to compare the price. Using prices[i] will iterate through all prices and it will compare them with 5. Using only the variable i will not iterate through the prices. This is only a number with a range from 0 to (the length of the quantity dictionary) -1.

Hope this helps.
Best,
Tsvetelin

Submit an answer