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?
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.
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.
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.
‘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.
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.
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!
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.
You have empty line
s in your input file and I suspect one of the line
s 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.
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}
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.
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