Search code examples
pythonpython-3.xiterable-unpacking

Python ValueError: too many values to unpack For Loop


Hi I have a DF i am trying to send to HTML table. For sample, here is the one and only row I have:

mdf = [('2007291533_946908J.70J.908J-06.FPP.FMGN512.rSBDl5kn9o4R4wP7dtmissbinallerrors.log', 'K946', 'nabcs', '027', 'ERROR: 2007291533_946908J.70J.908J-06.FPP.FMGN512.rSBDl5kn9o4R4wP7dtmissbinallerrors.loghas bad formatting because it has No product offset', 'C:\\Users\\error_dir\\2007291533_946908J.70J.908J-06.FPP.FMGN512.rSBDl5kn9o4R4wP7dtmissbinallerrors.log') ]

As you can see there are six items in the tuple

But when I try to unpack it in this:

for tup in mdf:
        for filename, lot, lot_owner, holder, error, location in tup:
            hlist.append(f"\n<tr><td>{filename}</td><td>{lot}</td><td>{lot_owner}</td><td>{holder}</td><td>{error}</td><td>{location}</td></tr>\n")

I get ValueError: too many values to unpack (expected 6)

How is this possible when I have 6 items in the second for loop?


Solution

  • That is because you are looping in the tuple.

    for item in tup:
        print(item) 
    

    Each iteration of item in tuple will give you each content of the tuple. Each item is going to be only one value (first iteration is going to be your filename, the second will be lot, etc). You cannot unpack 6 values from filename.

    Try

    for filename, lot, lot_owner, holder, error, location in mdf:
            hlist.append(f"\n<tr><td>{filename}</td><td>{lot}</td><td>{lot_owner}</td><td>{holder}</td><td>{error}</td><td>{location}</td></tr>\n")