Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python ValueError: too many values to unpack [duplicate]

Tags:

python

I am getting that exception from this code:

class Transaction:     def __init__ (self):         self.materials = {}      def add_material (self, m):         self.materials[m.type + m.purity] = m      def serialize (self):         ser_str = 'transaction_start\n'          for k, m in self.materials:             ser_str += m.serialize ()          sert += 'transaction_end\n'         return ser_str 

The for line is the one throwing the exception. The ms are Material objects. Anybody have any ideas why?

like image 704
Nik Avatar asked Aug 13 '11 21:08

Nik


People also ask

How do I fix ValueError too many values to unpack expected 3?

Conclusion # The Python "ValueError: too many values to unpack (expected 3) in Python" occurs when the number of variables in the assignment is not the same as the number of values in the iterable. To solve the error, declare exactly as many variables as there are items in the iterable.

What does too many values to unpack mean?

The valueerror: too many values to unpack occurs during a multiple-assignment where you either don't have enough objects to assign to the variables or you have more objects to assign than variables.

How do I fix ValueError is not enough values to unpack expected 3 got 2?

So there isn't any space for l in the student dictionary, and it throws the ValueError: not enough values to unpack (expected 3, got 2) . To fix this, you need to fix the variables of the dictionary. This is the correct statement to iterate over a dictionary in Python.


1 Answers

self.materials is a dict and by default you are iterating over just the keys (which are strings).

Since self.materials has more than two keys*, they can't be unpacked into the tuple "k, m", hence the ValueError exception is raised.

In Python 2.x, to iterate over the keys and the values (the tuple "k, m"), we use self.materials.iteritems().

However, since you're throwing the key away anyway, you may as well simply iterate over the dictionary's values:

for m in self.materials.itervalues(): 

In Python 3.x, prefer dict.values() (which returns a dictionary view object):

for m in self.materials.values(): 
like image 115
Johnsyweb Avatar answered Oct 22 '22 11:10

Johnsyweb