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 m
s are Material
objects. Anybody have any ideas why?
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.
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.
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.
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():
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With