Home > Mobile >  python dictionary type error sum wont calculate
python dictionary type error sum wont calculate

Time:10-10

def calculate_average_rating(input):
    final = {}
    for key in input.keys():
        avg = sum(input[key])/len(input[key])
        final[key] = avg
    return final

My code is intended to take a dictionary input, "The Lion King (2019)" : [6.0, 7.5, 5.1], "Titanic (1997)": [7], and calculate the average of the scores of each movie and return in a dictionary form. For example: "Spider-Man (2002)": [3,2,4,5]} ==> {"Spider-Man (2002)": 3.5

The error I'm getting is

TypeError                                 Traceback (most recent call last)
<ipython-input-134-8a09678d0016> in <module>
----> 1 calculate_average_rating(ratingData)

<ipython-input-133-3a0eaee00f3b> in calculate_average_rating(input)
      2     final = {}
      3     for key in input.keys():
----> 4         avg = sum(input[key])/len(input[key])
      5         final[key] = avg
      6     return final

TypeError: unsupported operand type(s) for  : 'int' and 'str'

CodePudding user response:

It looks like you need to pre-process the ratings:

def calculate_average_rating(ratings):
    final = {}
    for key in ratings.keys():
        film = [float(item) for item in ratings[key]]
        avg = sum(film)/len(film)
        final[key] = avg
    return final

CodePudding user response:

def calculate_average_rating(input):
    final = {}
    for key in input.keys():
        avg = sum(map(lambda x : int(x),input[key]))/len(input[key])
        final[key] = avg
    return final

CodePudding user response:

Try the 1 liner below

data = {"The Lion King (2019)" : [6.0, 7.5, 5.1], "Titanic (1997)": [7]}

avg = {k: sum(v)/len(v) for k,v in data.items()}
print(avg)

output

{'The Lion King (2019)': 6.2, 'Titanic (1997)': 7.0}
  • Related