简体   繁体   中英

While loop adding dictionary items

I am trying to add the [2] item of the dictionary for each key using a while loop. The [2] item is the money spent.

movies = {
   1:('The Shawshank Redemption' , 'Bob', 25, 5),
   2:('The Godfather', 'Kelly', 25, 4),
   3:('The Dark Knight', 'Tyler', 25, 3),
   4:('12 Angry Men', 'Bob', 25, 4),
   5:('The Shawshank Redemption' , 'Bill', 35, 4),
   6:('The Godfather', 'Sally', 35, 5),
   7:('The Dark Knight', 'Suzy', 19, 5),
   8:('12 Angry Men', 'Frank', 19, 3),
   9:('The Shawshank Redemption' , 'Sally', 35, 5),
   10:('The Godfather', 'Leslie', 40, 2),
   11:('The Green Knight', 'Tom', 35, 2),
   12:('14 Angry Men', 'Kaitlyn', 25, 4)}

Below is my code:

spent = 0
x = 1
while spent > 0:
   spent += movies[x][2]
   x += 1
else:
   print ('The total money spent is:', spent)

It doesn't seem to be looping or adding, I am new to this, thanks in advance.

spent is initailized to 0.

Therefore the condition spent > 0 is not true, so the loop does not execute.

The problem is in your while condition. You're setting spent to 0 and then saying that while it's greater than 0, it should add the amount spent on each movie.

What you should do is set the condition to add while x is less than the max key. Which you could obtain by just calling max(movies.keys()) .

This solution shouldn't be hard to implement. I won't provide the code solution, because it feels like solving your homework, but change the condition as I advised and it should work.

Also, as advised on a comment, a list for your movies would be better than a dict.

We want to avoid while loops as best as we can, in this case you can use a for loop and go through all the items and sum the values identical to your approach just change your loop type

spent = 0
for i in movies:
    spent += movies[i][2]
 chrx@chrx:~/python/stack$ python3.7 sum.py 343

For fun did this using reduce, not necessary

from functools import reduce
spent = reduce((lambda x, y: x + y), (movies[i][2] for i in movies))

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM