Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I fix ValueError: Too many values to unpack" in Python?

I am trying to populate a dictionary with the contents of my text file ("out3.txt").

My text file is of the form:

vs,14100

mln,11491

the,7973

cts,7757

...and so on...

I want my dictionary answer to be of the form:

answer[vs]=14100

answer[mln]=11491

...and so on...

My code is:

import os
import collections
import re
from collections import defaultdict

answer = {}
answer=collections.defaultdict(list)
with open('out3.txt', 'r+') as istream:
    for line in istream.readlines():
        k,v = line.strip().split(',')
        answer[k.strip()].append( v.strip())

But, I get:

ValueError: too many values to unpack

How can I fix this?

like image 229
Poker Face Avatar asked Jul 01 '13 11:07

Poker Face


People also ask

How do I stop too many values to unpack?

The most straightforward way of avoiding this error is to consider how many values you need to unpack and then have the correct number of available variables.

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?

The “ValueError: not enough values to unpack” error is raised when you try to unpack more values from an iterable object than those that exist. To fix this error, make sure the number of values you unpack from an iterable is equal to the number of values in that iterable.

What does ‘Python ValueError too many values to unpack (expected 2) ’ mean?

‘Python valueerror: too many values to unpack (expected 2)’ occurs when you are trying to access too many values from an iterator than expected. What is Unpacking? What exactly do we mean by Valueerror: too many values to unpack (expected 2)? Functions in python have the ability to return multiple variables.

How to unpack variables in Python?

Unpacking using tuple and list: When we write multiple variables on the left-hand side of the assignment operator separated by commas and tuple or list on the right-hand side, each tuple/list value will be assigned to the variables left-hand side. 2. Unpacking using underscore: Any unnecessary and unrequired values will be assigned to underscore.

Why does my Python list have too many variables?

Another common cause is when you try to unpack too many values into variables without assigning enough variables. You solve this issue by ensuring the number of variables to which a list unpacked is equal to the number of items in the list. Now you’re ready to solve this Python error like a coding ninja!

Does Python unpack a suitcase?

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email. Python does not unpack bags well. When you see the error “valueerror: too many values to unpack (expected 2)”, it does not mean that Python is unpacking a suitcase.


3 Answers

You have empty lines in your input file and I suspect one of the lines that you have not shared with us has too many commas in it (hence "too many values to unpack").

You can protect against this, like so:

import collections

answer = collections.defaultdict(list)
with open('out3.txt', 'r+') as istream:
    for line in istream:
        line = line.strip()
        try:
            k, v = line.split(',', 1)
            answer[k.strip()].append(v.strip())
        except ValueError:
            print('Ignoring: malformed line: "{}"'.format(line))

print(answer)

Note: By passing 1 into str.split(), everything after the first comma will be assigned to v; if this is not desired behaviour and you'd prefer these lines to be rejected, you can remove this argument.

like image 152
Johnsyweb Avatar answered Nov 01 '22 18:11

Johnsyweb


Your solution doesn't give your desired output. You'll have (assuming it worked), answer['vs'] = [14100], the below does what you intended:

import csv

with open('out3.txt') as f:
  reader = csv.reader(f, delimiter=',')
  answer = {line[0].strip():line[1].strip() for line in reader if line}
like image 26
Burhan Khalid Avatar answered Nov 01 '22 19:11

Burhan Khalid


You do not need the collections here. Plain old dict is enough:

answer = {}
with open('out3.txt', 'r+') as f:
    for line in f:
        lst = line.split(',')
        if len(lst) == 2:
            k = lst[0].strip()
            v = lst[1].strip()
            answer[k] = v

print(answer['mln'])
print(answer.get('xxx', 'not available'))

Notice the answer.get() is similar to answer[] but you can supply the defaul value.

You should not use .readlines() in the loop. Even the empty line contains the newline character. This way the test if line: does not detects the empty lines. Or you have to strip (or rstrip) it first, or you can split the line to the list and test the number of elements.

like image 26
pepr Avatar answered Nov 01 '22 17:11

pepr