-3

marks={'A':[50,70,90],'B':[60,80,70],'C':[70,80,90]}

In the above dictionary, I need to access the value of B and to find the average of list (i:e:(60+80+70)/3). How could I access the value and find the average? What I tried was...

marks={'A':[50,70,90],'B':[60,80,70],'C':[70,80,90]}
get_name=input()
for i in marks:
    if i==get_name:
        for j in i:
            add += marks[j]
print(add/3)

It shows up error. How to access the values in the dictionary of the list[60,80,70] with respect to key 'B'.

Krithick S
  • 408
  • 3
  • 15

3 Answers3

0

Here's a one liner -

avg = sum(marks['B'])/3
WeaselFox
  • 7,220
  • 8
  • 44
  • 75
0

sum() will total the value in that respective list and you just have to divide it by the size of the list.

input = 'A'
average = sum(marks[input])/len(marks[input])
Cheang Wai Bin
  • 133
  • 1
  • 7
0
marks={'A':[50,70,90],'B':[60,80,70],'C':[70,80,90]}

For the above code, marks[get_name] should print out the list [60,80,70] through which the mean can be then taken.

To iterate over a dictionary you would use, for key, val in marks.items() and check if the provided user input equals to one of the key and then take the average.

coldy
  • 2,115
  • 2
  • 17
  • 28