1

My Code:-

Videos10k=[{'title': '', 'titleWords': ['...','...'], 'titleLength': 10, 'likes': 86, 'disLikes': 5, 'views': 2202, 'creator': '...', 'description': '...'}]
def getavg(number, array=[]):
    views_avg = 0
    for idx, Video in array:
        views = Video["views"]
        views_avg = views_avg + views

    views_avg = views_avg / len(array)
    print("Average views for " + number + " " + views_avg)


getavg("10k", Videos10k)

I am getting this error. Error:-

in getavg for idx, Video in array: ValueError: too many values to unpack (expected 2)

sanket kheni
  • 1,482
  • 2
  • 12
  • 29
  • Not related to your question, but check https://stackoverflow.com/q/1132941/4046632 Don't use mutable default arguments. – buran Jun 20 '21 at 07:38

4 Answers4

6

You need to get item in array with just Video, not with idx, Video

Videos10k=[{'title': '', 'titleWords': ['...','...'], 'titleLength': 10, 'likes': 86, 'disLikes': 5, 'views': 2202, 'creator': '...', 'description': '...'}]
def getavg(number, array=[]):
    views_avg = 0
    for Video in array:
        views = Video["views"]
        views_avg = views_avg + float(views)

    views_avg = views_avg / len(array)
    print("Average views for " + str(number) + " " + str(views_avg))

Or you can change to like this

for idex, Video in enumerate(array):
puhuk
  • 464
  • 5
  • 15
5

enumerate function gives to index number.

Change your code like below

for idx, Video in enumerate(array):
MertG
  • 753
  • 1
  • 6
  • 22
  • 2
    Just to mention that actually `idx` is never used anywhere else in the code, i.e. it's redundant. – buran Jun 20 '21 at 07:41
  • 1
    @buran exception says that `in getavg for idx, Video in array: ValueError: too many values to unpack (expected 2)`. Even you are not using `idx`, code expects. – MertG Jun 20 '21 at 07:51
  • Exactly - one way to solve it is to add enumerate, the other (if idx is not needed) is to remove idx, like @puhuk did in their answer, instead of just keep the redundant idx. – buran Jun 20 '21 at 08:23
0

if you want to loop through the index of array you can use enumerate like this :

for idx, Video in enumerate(array):

or use zip :

for idx,Video in zip(range(len(array)),array):

in your code you never used idx so you don't need it .

Belhadjer Samir
  • 1,461
  • 7
  • 15
0

If you want to keep things Simple, Keep Videos10k as a dict and have the function handle the different type() of input.

Videos10k={'title': '', 'titleWords': ['...','...'], 'titleLength': 10, 'likes': 86, 'disLikes': 5, 'views': 2202, 'creator': '...', 'description': '...'}

def getAvg(number,array):
    if type(array) != list:
        print('Average Views For {}: {}'.format(number,array/len([array])))
    else:
        print('Average Views For {}: {}'.format(number,array/len(array)))



getAvg("10k", Videos10k['views'])
Pythonics
  • 122
  • 3