0

I am trying to count the number of names within a dictionary in order to use them in an equation (total marks/num of students.) I keep getting an error that tells me I cannot use the operand '+=:' with a str and an int but I don't know how I can convert the int to a str or viceversa in order for it to work.

for name in student_marks:
        total_marks+=student_marks.get(name)
        no_students+=1

avg_mark=total_marks/no_students
Cecilia
  • 4,512
  • 3
  • 32
  • 75
AlliD
  • 1

6 Answers6

0

Without seeing the structure of the student_marks I can only guess but...

for name, grade in student_marks.iteritems():
    total_marks += int(grade)
    no_students += 1

avg_mark = total_marks/no_students
cmeadows
  • 185
  • 2
  • 12
0

Alternatively:

scores = map(int, student_marks.values())
avg_mark = sum(scores)/len(scores)

If you fix your dict to have integer values, then you can drop the map(int, ...):

scores = student_marks.values()
avg_mark = sum(scores)/len(scores)

Example:

>>> student_marks = {"John": "83", "Bob": "21", "Henry": "100"}
>>> scores = map(int, student_marks.values())
>>> avg_mark = sum(scores)/len(scores)
>>> avg_mark
68
TemporalWolf
  • 7,727
  • 1
  • 30
  • 50
0

In a dictionary it is not necessary to have a string as both key and value. The key-value pair can consist of a string and an integer

student_marks = {
    'student1': 80,
    'student2': 95
}

total_marks = 0
no_students = 0

for name in student_marks:
    total_marks += student_marks.get(name)
    no_students += 1
ksasaoka
  • 41
  • 8
0

Your code is working as is. At-least with the sample dict I have. student_marks.get(name) will get student-marks as int.unless you have those defined as str. in which case you will need to transform those to int.

Did you define following?

total_marks = 0
no_students = 0

EDIT
Updated dict with string values instead of int.

Your Code with sample dict:

    student_marks = {'student1' : '89', 'student2' : '65','student3' : '94'}
total_marks = 0
no_students = 0

for name in student_marks:
        total_marks+=int(student_marks.get(name))        
        no_students+=1

avg_mark=total_marks/no_students
print avg_mark

Result:

Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>> 
82
>>> 
Anil_M
  • 10,893
  • 6
  • 47
  • 74
  • If the `values` are strings, you get `TypeError: unsupported operand type(s) for +=: 'int' and 'str'`, which is consistent with what the OP said in his description. – TemporalWolf Mar 15 '17 at 20:07
  • 1
    Yes, I updated `dict` with `str` values and recast values to `int`. – Anil_M Mar 15 '17 at 20:13
0

I assume the dict structure is as follows:

student_marks={'s1':10, 's2':9,...}
or
students_marks={'s1':'10', 's2':'9',...}

or a mix of both, in that case, you should be consistent with the type you're using as a value in a dictionary as much as you can, not that python would care it'll just throw TypeError at you, but to save yourself from possible headaches.

The problem you're getting may be caused by:

  1. total_marks isn't an integer and the dictionary values are integers, so you should make sure to initialize total_marks at the beginning of your code.

  2. The opposite case, total_marks is an integer but, a value (or several values) in the dict are strings. You should add a line in the for loop that converts from string to integer, and make sure that the string is is a numerical string before the conversion (you can't convert the string 'a' into an integer) by either using assert or a try/except.

  3. The code can be rewritten in a more, convenient way to catch some of the errors as follows:

    students_marks={'a':10, 'b':9, 'c':5,...}
    total_marks=0
    
    #this loop iterates over the keys(in this case the students names) in the dictionary
    for name in students_marks.keys():
        try:
            total_marks+= int(student_marks[name])
            #alternatively
            #total_marks+= int(student_marks.get(name,0))
        except:
            #this line will print out the incorrect entry in the dictionary.
            print('Student {} marks are incorrect, {}'.format(name, student_marks[name]))
    
    average_marks=total_marks/len(students_marks)
    

If the dictionary values are all correct, you can go:

    total_marks=sum(student_marks.values())
    number_of_students=len(students_marks)
    average_marks=total_marks/number_of_students

You can also cram the previous code in a single line, depends on what do you need from your code.

-1

sum all values / number of student

 sum(map( int, student_marks.values()) )/len(student_marks)
galaxyan
  • 5,944
  • 2
  • 19
  • 43