Home > Net >  Python Dictionary - using input to add up all of the values in a dictionary
Python Dictionary - using input to add up all of the values in a dictionary

Time:11-14

I am about half way through an intro to python course. I very recently started studying lists/dictionaries. I was trying to create my own python code to try to learn how to work with dictionaries better. Basically, what I am trying to do is get a user's input as to what section of a video series they are on and then output the total time left in the series. So far the code looks something like this:

video_dict = {
    1 : 9,   # Section 1 is 9 minutes
    2 : 75,
    3 : 174,
    4 : 100
}

current_section = input('What section are you currently on?')

total_time = 0
for key, value in video_dict.items():
    if current_section >= key:
    total_time  = value

print(total_time)
     

The issue I have had so far is that it seems to be taking the number entered by the user and going in reverse up the dictionary. So if you enter '2' as your current section, it adds up entry 1 and 2 and gives you a total_time of 84 minutes; instead of adding up 2,3, and 4 for a total time of 349 minutes. What do i need to correct to get it to go down the list instead of up it?

CodePudding user response:

Your code looks so close to being correct. I made a slight modification, but otherwise it's all your code:

video_dict = {
    1 : 9,   # Section 1 is 9 minutes
    2 : 75,
    3 : 174,
    4 : 100
}



current_section = int(input('What section are you currently on?'))

total_time = 0
for key, value in video_dict.items():
    if current_section <= key :
      total_time  = value

print(total_time)

The modification I made current_section >= key to current_section <= key

CodePudding user response:

video_dict = {
    1 : 9,   # Section 1 is 9 minutes
    2 : 75,
    3 : 174,
    4 : 100
}

inp = int(input('What section are you currently on?'))
res = 0
for key in range(inp,0,-1):
    res =video_dict[key]


 print(res)

CodePudding user response:

Basically, what I am trying to do is get a user's input as to what section of a video series they are on and then output the total time left in the series

How about using a list ?

sections = [9, 75, 174, 100]

current_section = int(input('What section are you currently on?')) - 1
time_left = sum(sections[current_section:])
print(f'{time_left} minutes left')
  • Related