The “valueerror: too many values to unpack (expected 2)” error occurs when you do not unpack all the items in a list. This error is often caused by trying to iterate over the items in a dictionary. To solve this problem, use the items() method to iterate over a dictionary.
ValueError: too many values to unpack (expected 2) occurs when there is a mismatch between the returned values and the number of variables declared to store these values. If you have more objects to assign and fewer variables to hold, you get a value error.
So there isn't any space for l in the student dictionary, and it throws the ValueError: not enough values to unpack (expected 3, got 2) . To fix this, you need to fix the variables of the dictionary. This is the correct statement to iterate over a dictionary in Python.
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.
In the Python tutorial book I'm using, I typed an example given for simultaneous assignment. I get the aforementioned ValueError when I run the program, and can't figure out why.
Here's the code:
#avg2.py
#A simple program to average two exam scores
#Illustrates use of multiple input
def main():
print("This program computes the average of two exam scores.")
score1, score2 = input("Enter two scores separated by a comma: ")
average = (int(score1) + int(score2)) / 2.0
print("The average of the scores is:", average)
main()
Here's the output.
>>> import avg2
This program computes the average of two exam scores.
Enter two scores separated by a comma: 69, 87
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
import avg2
File "C:\Python34\avg2.py", line 13, in <module>
main()
File "C:\Python34\avg2.py", line 8, in main
score1, score2 = input("Enter two scores separated by a comma: ")
ValueError: too many values to unpack (expected 2)
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