Too many values to unpack Exception
That exception means that you are trying to unpack a tuple, but the tuple has too many values with respect to the number of target variables. For example: this work, and prints 1, then 2, then 3
def returnATupleWithThreeValues():
return (1,2,3)
a,b,c = returnATupleWithThreeValues()
print a
print b
print c
But this raises your error
def returnATupleWithThreeValues():
return (1,2,3)
a,b = returnATupleWithThreeValues()
print a
print b
raises
Traceback (most recent call last):
File "c.py", line 3, in ?
a,b = returnATupleWithThreeValues()
ValueError: too many values to unpack
Now, the reason why this happens in your case, I don't know, but maybe this answer will point you in the right direction.
ValueError: too many values to unpack (expected 4) during ORB detection
In match_keypoints
you have (at least) two return
statements.
One of them, in the except
block returns 5 elements , None, None, [], [], None
.
The other returns 4 elements, return keypoints_needle, keypoints_haystack, good, points
Thus, whenever match_keypoints
encounters cv.error
in that try
block, it will return 5 elements, which is one more than you attempt to dereference in the line that is failing: kp1, kp2, matches, match_points = objectToFind.match_keypoints(keypoint_image)
Too many values to unpack
is the error that occurs when the returned tuple has more elements than the number of variables on the LHS of the assignment.
ValueError: too many values to unpack (expected 2) when trying to iterate over twolists at the same time
If you want to iterate over 2 lists in same moment, you should use zip()
funciton.
Example:
>>> lol = [1,2,3,4,5]
>>> kek = [6,7,8,9,10]
>>> for num, secnum in zip(lol, kek):
... print(num, secnum)
Let me explain why you can't "unpack" it.
For example, lets say that we have this list:arr = [1, 2, 3, 4, 5]
. On every iteration you can get only 1 object, right?
one = arr[0]
two = arr[2]
...
So that's how we could get values from list.
We can assign values like this too:
one, two, three = arr[0], arr[1], arr[2]
In python there is *
sign, means that you could 'pack' value in list.
colors = ['cyan', 'magenta', 'yellow', 'black']
cyan, magenta, *other = colors
print(cyan)
print(magenta)
print(other)
Output:
cyan
magenta
['yellow', 'black']
Summary what unpucking do:
- Unpacking assigns elements of the list to multiple variables.
- Use the asterisk (*) in front of a variable like this *variable_name to pack the leftover elements of a list into another list.
I want to resolve the error ValueError: too many values to unpack (expected 2)
It is caused by wrong arguments you passed to sg.Text
.
layout = [
[sg.Text('When will it start?', start)],
[sg.Text('When will it end?', end)],
[sg.Text('Where will it be?', location)]
]
For sg.Text.__init__
,
def __init__(self, text='', size=(None, None), auto_size_text=None, click_submits=False, enable_events=False, relief=None, font=None, text_color=None, background_color=None, border_width=None, justification=None, pad=None, key=None, k=None, right_click_menu=None, grab=None, tooltip=None, visible=True, metadata=None):
If you didn't use the keyword for each keyword arguments, then text
will be 'When will it start?', size
will be start
in case
sg.Text('When will it start?', start)
option size
as a two-tuple (width, height)
, but you just give it one string, so it got the exception,
ValueError: too many values to unpack (expected 2)
You can solve it by
sg.Text(' '.join(['When will it start?', str(start)]))
Python ValueError: too many values to unpack
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():
Error: 'too many values to unpack (expected 2) when applying a function
The line sib, parch = passenger
assumes that passenger
has two elements, which you're trying to assign to sib
and parch
. The error is saying that two elements were expected (one for sib
, one for parch
), but that only one was supplied (passenger
).
If you're trying to apply accompany_alone()
across each row, it could be easier to just iterate over the row indices explicitly, for example something like this would work:
def accompany_alone(sib, arch):
if sib > 0: return 'With Family'
elif parch > 0: return 'With Family'
else: return 'Alone'
titanic_df['Alone'] = [accompany_alone(titanic_df['SibSp'][idx],
titanic_df['Parch'][idx])
for idx in range(titanic_df.shape[0])]
Also try playing around with the axis
parameter of DataFrame.apply()
-- it might not be behaving as you expect (here's a link to the docs).
ValueError: too many values to unpack (expected 2) when passing values from dictionary
You're making PList
a tuple of lists. You want a list of tuples. Use zip()
for that.
PList = list(zip(self._fi_apps_list, man_list))
ValueError: too many values to unpack(expected 2) - train_test_split
You should use zip to group the variables in a python iterator:
for x,y in zip(X_test,y_test):
extract_features(x, y, model, plain_samples , plain_labels )
Explanation
When you pass multiple values to the right side of a for statement python interprets it as a tuple so it will expect one variable to unpack. Example:
poo = ("one", "two", "three", "four")
foo = [1, 2, 3, 4]
for x in poo, foo: # Equals to for x in (poo, foo):
print(x)
Output:
('one', 'two', 'three', 'four')
[1, 2, 3, 4]
Using Zip
If you want to group two iterables in a way that in each iteration the i-th tuple contains the i-th element from each of the items you should use the zip built-in python function (there are also other functions that group the iterables using other criteria in the itertools package).
Example:
poo = ("one", "two", "three", "four")
foo = [1, 2, 3, 4]
for x, y in zip(poo, foo):
print(f"{x}: {y}")
Output:
one: 1
two: 2
three: 3
four: 4
Related Topics
Using Pandas .Append Within for Loop
How to Run Python Code from Sublime Text 2
Differencebetween 'Same' and 'Valid' Padding in Tf.Nn.Max_Pool of Tensorflow
Label Python Data Points on Plot
Get the Second Largest Number in a List in Linear Time
Selenium Compound Class Names Not Permitted
How to Print Unicode Character in Python
"Too Many Values to Unpack" Exception
Relative Imports - Modulenotfounderror: No Module Named X
Elegant Python Function to Convert Camelcase to Snake_Case
Extracting Date from a String in Python
Reconstruct a Categorical Variable from Dummies in Pandas