Connecting Tech Pros Worldwide Help | Site Map

ValueError: too many values to unpack

Newbie
 
Join Date: Sep 2009
Posts: 2
#1: Sep 30 '09
Hello all!
I think there are some people here to help me
Of course I did some search, similar topic (that I walked through) did not discuss for loops
My problem is this error: ValueError: too many values to unpack (in line 4)

I have a function for getting the average of a dictionary!
(sorry! new to python)
I have summarized the code and printed the variable sumPerYear so you can have a quick look:
Expand|Select|Wrap|Line Numbers
  1. def average(array):
  2.     total=0.0
  3.     size=len(array)
  4.     for (name,item) in array:
  5.         print item
  6.         total=total+float(item)
  7.  
  8.     avg=total/size
  9.     return avg
  10.  
  11.  
  12. sumPerYear={'1999': 3723.18, '1995': 3999.05, '1997': 4225, '2005': 3946, '1991': 4191, '2003': 3862, '1993': 4377.27, '2001': 3509.27, '1998': 3738.64, '1994': 3952.5, '2004': 3905., '1996': 3859.59, '2002': 3865.77, '1990': 4172.64, '2000': 3853.36, '1992': 4708.95}
  13. print(average(sumPerYear))
Many thanks for you help
Newbie
 
Join Date: Sep 2009
Location: New Hampshire, USA
Posts: 3
#2: Sep 30 '09

re: ValueError: too many values to unpack


If you iterate over a dictionary, it will iterate over just the keys, not key-value tuples. You want to say "for name in array:" and then "print array[name]" and so forth. Alternatively, you could say "for (name, item) in array.items():" and then the rest of your code would work the way you want it to, since the dict.items method does return key-value tuples. The first way is more efficient, though.

EDIT: You can actually accomplish all of this much more efficiently and with a lot less code. Try this:
Expand|Select|Wrap|Line Numbers
  1. def average(array):
  2.     return float(sum(array.values())) / len(array)
Reply