Fix Python – Python ValueError: too many values to unpack [duplicate]


Asked By – Nik

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?

Now we will see solution for issue: Python ValueError: too many values to unpack [duplicate]


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 tuplek, m“, hence the ValueError exception is raised.

In Python 2.x, to iterate over the keys and the values (the tuplek, 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():

This question is answered By – johnsyweb

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0