Python ValueError: too many values to unpack For Loop

3.7k Views Asked by At

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?

3

There are 3 best solutions below

10
On BEST ANSWER

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")
4
On

You have a list of tuples, you are unpacking it at the wrong level, I guess.

Isn't this what you need?

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")
5
On

So, basically, you simply need to unpack tuple. I think you're going a bit too complicated and I'm not sure why no one has suggested it yet, but the simplest way to do it will be:

for tup in mdf:
    filename, lot, lot_owner, holder, error, location = 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")

There's really no need for a second for loop.