Valueerror too many values to unpack expected 2 python ошибка

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:Python34avg2.py", line 13, in <module>
    main()
  File "C:Python34avg2.py", line 8, in main
    score1, score2 = input("Enter two scores separated by a comma: ")
ValueError: too many values to unpack (expected 2)

asked Jun 10, 2014 at 21:15

Ziggy's user avatar

2

Judging by the prompt message, you forgot to call str.split at the end of the 8th line:

score1, score2 = input("Enter two scores separated by a comma: ").split(",")
#                                                                ^^^^^^^^^^^

Doing so splits the input on the comma. See a demonstration below:

>>> input("Enter two scores separated by a comma: ").split(",")
Enter two scores separated by a comma: 10,20
['10', '20']
>>> score1, score2 = input("Enter two scores separated by a comma: ").split(",")
Enter two scores separated by a comma: 10,20
>>> score1
'10'
>>> score2
'20'
>>>

answered Jun 10, 2014 at 21:16

The above code will work fine on Python 2.x. Because input behaves as raw_input followed by a eval on Python 2.x as documented here — https://docs.python.org/2/library/functions.html#input

However, above code throws the error you mentioned on Python 3.x. On Python 3.x you can use the ast module’s literal_eval() method on the user input.

This is what I mean:

import ast

def main():
    print("This program computes the average of two exam scores.")

    score1, score2 = ast.literal_eval(input("Enter two scores separated by a comma: "))
    average = (int(score1) + int(score2)) / 2.0

    print("The average of the scores is:", average)

main()

answered Jun 10, 2014 at 21:17

shaktimaan's user avatar

shaktimaanshaktimaan

11.9k2 gold badges29 silver badges33 bronze badges

1

This is because behavior of input changed in python3

In python2.7 input returns value and your program work fine in this version

But in python3 input returns string

try this and it will work fine!

score1, score2 = eval(input("Enter two scores separated by a comma: "))

answered May 3, 2017 at 6:55

DexJ's user avatar

DexJDexJ

1,26413 silver badges24 bronze badges

that means your function return more value!

ex:

in python2 the function cv2.findContours() return —> contours, hierarchy

but in python3 findContours(image, mode, method[, contours[, hierarchy[, offset]]]) -> image, contours, hierarchy

so when you use those function, contours, hierachy = cv2.findContours(...) is well by python2, but in python3 function return 3 value to 2 variable.

SO ValueError: too many values to unpack (expected 2)

answered Aug 30, 2017 at 2:59

X.Na's user avatar

На чтение 5 мин Просмотров 19.6к. Опубликовано 22.11.2021

В этой статье мы рассмотрим из-за чего возникает ошибка ValueError: too many values to unpack и как ее исправить в Python.

Содержание

  1. Введение
  2. Что такое распаковка в Python?
  3. Распаковка списка в Python
  4. Распаковка списка с использованием подчеркивания
  5. Распаковка списка с помощью звездочки
  6. Что значит ValueError: too many values to unpack?
  7. Сценарий 1: Распаковка элементов списка
  8. Решение
  9. Сценарий 2: Распаковка словаря
  10. Решение
  11. Заключение

Введение

Если вы получаете ValueError: too many values to unpack (expected 2), это означает, что вы пытаетесь получить доступ к слишком большому количеству значений из итератора.

Ошибка Value Error — это стандартное исключение, которое может возникнуть, если метод получает аргумент с правильным типом данных, но недопустимым значением, или если значение, предоставленное методу, выходит за пределы допустимого диапазона.

В этой статье мы рассмотрим, что означает эта ошибка, в каких случаях она возникает и как ее устранить на примерах.

Что такое распаковка в Python?

В Python функция может возвращать несколько значений, и они могут быть сохранены в переменной. Это одна из уникальных особенностей Python по сравнению с другими языками, такими как C++, Java, C# и др.

Распаковка в Python — это операция, при которой значения итерабильного объекта будут присвоена кортежу или списку переменных.

Распаковка списка в Python

В этом примере мы распаковываем список элементов, где каждый элемент, который мы возвращаем из списка, должен присваиваться переменной в левой части для хранения этих элементов.

one, two, three = [1, 2, 3]

print(one)
print(two)
print(three)

Вывод программы

Распаковка списка с использованием подчеркивания

Подчеркивание чаще всего используется для игнорирования значений; когда _ используется в качестве переменной, когда мы не хотим использовать эту переменную в дальнейшем.

one, two, _ = [1, 2, 3]

print(one)
print(two)
print(_)

Вывод программы

Распаковка списка с помощью звездочки

Недостаток подчеркивания в том, что оно может хранить только одно итерируемое значение, но что если у вас слишком много значений, которые приходят динамически?

Здесь на помощь приходит звездочка. Мы можем использовать переменную со звездочкой впереди для распаковки всех значений, которые не назначены, и она может хранить все эти элементы.

one, two, *z = [1, 2, 3, 4, 5, 6, 7, 8]

print(one)
print(two)
print(z)

Вывод программы

После того, как мы разобрались с распаковкой можно перейти к нашей ошибке.

Что значит ValueError: too many values to unpack?

ValueError: too many values to unpack возникает при несоответствии между возвращаемыми значениями и количеством переменных, объявленных для хранения этих значений. Если у вас больше объектов для присвоения и меньше переменных для хранения, вы получаете ошибку значения.

Ошибка возникает в основном в двух сценариях

Сценарий 1: Распаковка элементов списка

Давайте рассмотрим простой пример, который возвращает итерабильный объект из четырех элементов вместо трех, и у нас есть три переменные для хранения этих элементов в левой части.

В приведенном ниже примере у нас есть 3 переменные one, two, three но мы возвращаем 4 итерабельных элемента из списка.

one, two, three = [1, 2, 3, 4]

Вывод программы

Traceback (most recent call last):
  File "/Users/krnlnx/Projects/Test/test.py", line 1, in <module>
    one, two, three = [1, 2, 3, 4]
ValueError: too many values to unpack (expected 3)

Решение

При распаковке списка в переменные количество переменных, которые вы хотите распаковать, должно быть равно количеству элементов в списке.

Если вы уже знаете количество элементов в списке, то убедитесь, что у вас есть равное количество переменных в левой части для хранения этих элементов для решения.

Если вы не знаете количество элементов в списке или если ваш список динамический, то вы можете распаковать список с помощью оператора звездочки. Это обеспечит хранение всех нераспакованных элементов в одной переменной с оператором звездочка.

Сценарий 2: Распаковка словаря

В Python словарь — это набор неупорядоченных элементов, содержащих пары ключ-значение. Рассмотрим простой пример, который состоит из трех ключей, и каждый из них содержит значение, как показано ниже.

Если нам нужно извлечь и вывести каждую из пар ключ-значение в словаре, мы можем использовать итерацию элементов словаря с помощью цикла for.

Давайте запустим наш код и посмотрим, что произойдет

city = {"name": "Saint Petersburg", "population": 5000000, "country": "Russia"}

for k, v in city:
    print(k, v)

Вывод программы

Traceback (most recent call last):
  File "/Users/krnlnx/Projects/Test/test.py", line 3, in <module>
    for k, v in city:
ValueError: too many values to unpack (expected 2)

В приведенном выше коде мы получаем ошибку, потому что каждый элемент в словаре «city» является значением.

В Python мы не должны рассматривать ключи и значения в словаре как две отдельные сущности.

Решение

Мы можем устранить ошибку с помощью метода items(). Функция items() возвращает объект представления, который содержит обе пары ключ-значение, сохраненные в виде кортежей.

Подробнее про итерацию словаря читайте по ссылке.

city = {"name": "Saint Petersburg", "population": 5000000, "country": "Russia"}

for k, v in city.items():
    print(k, v)

Вывод программы

name Saint Petersburg
population 5000000
country Russia

Примечание: Если вы используете Python 2.x, вам нужно использовать функцию iteritems() вместо функции items().

Заключение

В этой статье мы рассмотрели, почему в Python возникает ошибка «ValueError: too many values to unpack », разобрались в причинах и механизме ее возникновения. Мы также увидели, что этой ошибки можно избежать.

ValueError: too many values to unpack

Unpacking refers to retrieving values from a list and assigning them to a list of variables. This error occurs when the number of variables doesn’t match the number of values. As a result of the inequality, Python doesn’t know which values to assign to which variables, causing us to get the error ValueError: too many values to unpack.

Today, we’ll look at some of the most common causes for this ValueError. We’ll also consider the solutions to these problems, looking at how we can avoid any issues.

One of the most frequent causes of this error occurs when unpacking lists.

Let’s say you’ve got a list of kitchen appliances, where you’d like to assign the list values to a couple of variables. We can emulate this process below:

appliances = ['Fridge', 'Microwave', 'Toaster']
appliance_1, appliance_2 = appliances

Out:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-4-2c62c443595d> in <module>
      1 appliances = ['Fridge', 'Microwave', 'Toaster']
----> 2 appliance_1, appliance_2 = appliances

ValueError: too many values to unpack (expected 2)

We’re getting this traceback because we’re only assigning the list to two variables when there are three values in the list.

As a result of this, Python doesn’t know if we want Fridge, Microwave or Toaster. We can quickly fix this:

appliances = ['Fridge', 'Microwave', 'Toaster']
appliance_1, appliance_2, appliance_3 = appliances

With the addition of applicance_3, this snippet of code runs successfully since we now have an equal amount of variables and list values.

This change communicates to Python to assign Fridge, Microwave, and Toaster to appliance_1, appliance_2, and appliance_3, respectively.

Let’s say we want to write a function that performs computations on two variables, variable_1 and variable_2, then return the results for use elsewhere in our program.

Specifically, here’s a function that gives us the sum, product and quotient of two variables:

def compute(x, y): 
    sum = x + y
    product = x * y
    quotient = x / y
    return sum, product, quotient

result_1, result_2 = compute(12, 5)

Out:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-5-9e571b686b4f> in <module>
      6     return sum, product, quotient
      7 
----> 8 result_1, result_2 = compute(12, 5)

ValueError: too many values to unpack (expected 2)

This error is occurs because the function returns three variables, but we are only asking for two.

Python doesn’t know which two variables we’re looking for, so instead of assuming and giving us just two values (which could break our program later if they’re the wrong values), the value error alerts us that we’ve made a mistake.

There are a few options that you can use to capture the function’s output successfully. Some of the most common are shown below.

First we’ll define the function once more:

def compute(x, y): 
    sum = x + y
    product = x * y
    quotient = x / y
    return sum, product, quotient

Option 1: Assign return values to three variables.

result_1, result_2, result_3 = compute(12, 5)

print(f"Option 1: sum={result_1}, product={result_2}, quotient={result_3}")

Out:

Option 1: sum=17, product=60, quotient=2.4

Now that Python can link the return of sum, product, and quotient directly to result_1, result_2, and result_3, respectively, the program can run without error.

Option 2: Use an underscore to throw away a return value.

result_1, result_2, _ = compute(12, 5)

print(f"Option 2: sum={result_1}, product={result_2}")

Out:

Option 2: sum=17, product=60

The standalone underscore is a special character in Python that allows you to throw away return values you don’t want or need. In this case, we don’t care about the quotient return value, so we throw it away with an underscore.

Option 3: Assign return values to one variable, which then acts like a tuple.

results = compute(12, 5)

print(f"Option 3: sum={results[0]}, product={results[1]}, quotient={results[2]}")

Out:

Option 3: sum=17, product=60, quotient=2.4

With this option, we store all return values in results, which can then be indexed to retrieve each result. If you end up adding more return values later, nothing will break as long as you don’t change the order of the return values.

This ValueError can also occur when reading files. Let’s say we have records of student test results in a text file, and we want to read the data to conduct further analysis. The file test_results.txt looks like this:

80,76,84 83,81,71 89,67,,92 73,80,83

Using the following script, we could create a list for each student, which stores all of their test results after iterating through the lines in the txt file:

with open('test_results.txt', 'r') as f:
    file_content = f.read()

file_lines = file_content.split('n') # split file into a list of lines

student_1_scores, student_2_scores, student_3_scores = [], [], []

for line in file_lines:
    student_1_score, student_2_score, student_3_score = line.split(',')
    student_1_scores.append(student_1_score)
    student_2_scores.append(student_2_score)
    student_3_scores.append(student_3_score)

Out:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-14-70781b12ee1c> in <module>
      7 
      8 for line in file_lines:
----> 9     student_1_score, student_2_score, student_3_score = line.split(',')
     10     student_1_scores.append(student_1_score)
     11     student_2_scores.append(student_2_score)
ValueError: too many values to unpack (expected 3)

If you look back at the text file, you’ll notice that the third line has an extra comma. The line.split(',') code causes Python to create a list with four values instead of the three values Python expects.

One possible solution would be to edit the file and manually remove the extra comma, but this would be tedious to do with a large file containing thousands of rows of data.

Another possible solution could be to add functionality to your script which skips lines with too many commas, as shown below:

with open('test_results.txt', 'r') as f:
    file_content = f.read()

file_lines = file_content.split('n')

student_1_scores, student_2_scores, student_3_scores = [], [], []

for index, line in enumerate(file_lines):
    try:
        student_1_score, student_2_score, student_3_score = line.split(',')
    except ValueError:
        print(f'ValueError row {index + 1}')
        continue
        
    student_1_scores.append(student_1_score)
    student_2_scores.append(student_2_score)
    student_3_scores.append(student_3_score)

We use try except to catch any ValueError and skip that row. Using continue, we can bypass the rest of the for loop functionality. We’re also printing the problematic rows to alert the user, which allows them to fix the file. In this case, we get the message shown in the output for our code above, alerting the user that line 3 is causing an error.

We get this error when there’s a mismatch between the number of variables to the amount of values Python receives from a function, list, or other collection.

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. In situations where the number of values to unpack could vary, the best approaches are to capture the values in a single variable (which becomes a tuple) or including features in your program that can catch these situations and react to them appropriately.

Errors are illegal operations or mistakes. As a result, a program behaves unexpectedly. In python, there are three types of errors – Syntax errors, logic errors, and exceptions. Valuerror is one such error. Python raises valueerror when a function receives an argument that has a correct type but an invalid value. ‘Python valueerror: too many values to unpack (expected 2)’ occurs when you are trying to access too many values from an iterator than expected.

Functions in python have the ability to return multiple variables. These multiple values returned by functions can be stored in other variables. ‘Python valueerror: too many values to unpack (expected 2)’ occurs when more objects have to be assigned variables than the number of variables or there aren’t enough objects present to assign to the variables.

What is Unpacking?

Unpacking in python refers to the operation where an iterable of values must be assigned to a tuple or list of variables. The three ways for unpacking are:

1. 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.

Example:

x,y,z = [10,20,30]
print(x)
print(y)
print(z)

Output is:

10
20
30

2. Unpacking using underscore:

Any unnecessary and unrequired values will be assigned to underscore.

Example:

x,y,_ = [10,20,30]
print(x)
print(y)
print(_)

Output is:

10
20
30

3. Unpacking using asterisk(*):

When the number of variables is less than the number of elements, we add the elements together as a list to the variable with an asterisk.

Example:

x,y,*z = [10,20,30,40,50]
print(x)
print(y)
print(z)

Output is:

10
20
[30, 40, 50]

We unpack using an asterisk in the case when we have a function receiving multiple arguments. And we want to call this function by passing a list containing the argument values.

def my_func(x,y,z):
    print(x,y,z)
 
my_list = [10,20,30]
 
my_func(my_list)#This throws error

The above code shall throw an error because it will consider the list ‘my_list’ as a single argument. Thus, the error thrown will be:

      4 my_list = [10,20,30]
      5 
----> 6 my_func(my_list)#This throws error

TypeError: my_func() missing 2 required positional arguments: 'y' and 'z'

To resolve the error, we shall pass my_list by unpacking with an asterisk.

def my_func(x,y,z):
    print(x,y,z)
 
my_list = [10,20,30]
 
my_func(*my_list)

Now, it shall print the output.

10 20 30

What exactly do we mean by Valueerror: too many values to unpack (expected 2)?

The error message indicates that too many values are being unpacked from a value. The above error message is displayed in either of the below two cases:

  1. While unpacking every item from a list, not every item was assigned a variable.
  2. While iterating over a dictionary, its keys and values are unpacked separately.

Also, Read | [Solved] ValueError: Setting an Array Element With A Sequence Easily

Valueerror: too many values to unpack (expected 2) while working with dictionaries

In python, a dictionary is a set of unordered items. Each dictionary is stored as a key-value pair. Lets us consider a dictionary here named college_data. It consists of three keys: name, age, and grade. Each key has a respective value stored against it. The values are written on the right-hand side of the colon(:),

college_data = {
      'name' : "Harry",
      'age' : 21,
      'grade' : 'A',
}

Now, to print keys and values separately, we shall try the below code snippet. Here we are trying to iterate over the dictionary values using a for loop. We want to print each key-value pair separately. Let us try to run the below code snippet.

for keys, values in college_data:
  print(keys,values)

It will throw a ‘Valueerror: too many values to unpack (expected 2)’ error on running the above code.

----> 1 for keys, values in college_data:
      2   print(keys)
      3   print(values)

ValueError: too many values to unpack (expected 2)

This happens because it does not consider keys and values are separate entities in our ‘college_data’ dictionary.

For solving this error, we use the items() function. What do items() function do? It simply returns a view object. The view object contains the key-value pairs of the college_data dictionary as tuples in a list.

for keys, values in college_data.items():
  print(keys,values)

Now, it shall now display the below output. It is printing the key and value pair.

name Harry
age 21
grade A

Valueerror: too many values to unpack (expected 2) while unpacking a list to a variable

Another example where ‘Valueerror: too many values to unpack (expected 2)’ is given below.

Example: Lets us consider a list of length four. But, there are only two variables on the left hand of the assignment operator. So, it is likely that it would show an error.

var1,var2=['Learning', 'Python', 'is', 'fun!']

The error thrown is given below.

ValueError                            Traceback (most recent call last)
<ipython-input-9-cd6a92ddaaed> in <module>()
----> 1 var1,var2=['Learning', 'Python', 'is', 'fun!']

ValueError: too many values to unpack (expected 2)

While unpacking a list into variables, the number of variables you want to unpack must be equal to the number of items in the list.

The problem can be avoided by checking the number of elements in the list and have the exact number of variables on the left-hand side. You can also unpack using an asterisk(*). Doing so will store multiple values in a single variable in the form of a list.

var1,var2, *temp=['Learning', 'Python', 'is', 'fun!']

In the above code, var1 and var2 are variables, and the temp variable is where we shall be unpacking using an asterisk. This will assign the first two strings to var1 and var2, respectively, and the rest of the elements would be stored in the temp variable as a list.

The output is:

Learning Python ['is', 'fun!']

Valueerror: too many values to unpack (expected 2) while using functions

Another example where Valueerror: too many values to unpack (expected 2) is thrown is calling functions.

Let us consider the python input() function. Input() function reads the input given by the user, converts it into a string, and assigns the value to the given variable.

Suppose if we want to input the full name of a user. The full name shall consist of first name and last name. The code for that would be:

fname, lname = input('Enter Name:')

It would list it as a valueerror because it expects two values, but whatever you would give as input, it would consider it a single string.

Enter Name:Harry Potter
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-7-4d08b7961d29> in <module>()
----> 1 fname, lname = input('Enter Name:')

ValueError: too many values to unpack (expected 2)

So, to solve the valuerror, we can use the split() function here. The split() method in python is returning a list of substrings from a given string. The substring is created based on the delimiter mentioned: a space(‘ ‘) by default. So, here, we have to split a string containing two subparts.

fname, lname = input('Enter Name:').split()

Now, it will not throw an error.

Summarizing the solutions:

  • Match the numbers of variables with the list elements
  • Use a loop to iterate over the elements one at a time
  • While separating key and value pairs in a dictionary, use items()
  • Store multiple values while splitting into a list instead or separate variables

FAQ’s

Q. Difference between TypeError and ValueError.

A. TypeError occurs when the type of the value passed is different from what was expecting. E.g., When a function was expecting an integer argument, but a list was passed. Whereas, ValueError occurs when the value mentioned is different than what was expected. E.g., While unpacking a list, the number of variables is less than the length of the list.

Q. What is valueerror: too many values to unpack (expected 2) for a tuple?

A. The above valuerror occurs while working with a tuple for the same reasons while working with a list. When the number of elements in the tuple is less than or greater than the number of variables for unpacking, the above error occurs.

Happy Learning!

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. It means you are trying to access too many values from an iterator.

In this guide, we talk about what this error means and why it is raised. We walk through an example code snippet with this error so you can learn how to solve it.

Get offers and scholarships from top coding schools illustration

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses

Select your interest

First name

Last name

Email

Phone number

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.

The Problem: valueerror: too many values to unpack (expected 2)

A ValueError is raised when you try to access information from a value that does not exist. Values can be any object such as a list, a string, or a dictionary.

Let’s take a look at our error message:

valueerror: too many values to unpack (expected 2)

In Python, “unpacking” refers to retrieving items from a value. For instance, retrieving items from a list is referred to as “unpacking” that list. You view its contents and access each item individually.

The error message above tells us that we are trying to unpack too many values from a value. 

There are two mistakes that often cause this error:

  • When you try to iterate over a dictionary and unpack its keys and values separately.
  • When you forget to unpack every item from a list to a variable.

We look at each of these scenarios individually.

Example: Iterating Over a Dictionary

Let’s try to iterate over a dictionary. The dictionary over which we will iterate will store information about an element on the periodic table. First, let’s define our dictionary:

hydrogen = {
	"name": "Hydrogen",
	"atomic_weight": 1.008,
	"atomic_number": 1
}

Our dictionary has three keys and three values. The keys are on the left of the colons; the values are on the right of the colons. We want to print out both the keys and the values to the console. To do this, we use a for loop:

for key, value in hydrogen:
	print("Key:", key)
	print("Value:", str(value))

In this loop, we unpack “hydrogen” into two values: key and value. We want “key” to correspond to the keys in our dictionary and “value” to correspond to the values.

Let’s run our code and see what happens:

Traceback (most recent call last):
  File "main.py", line 8, in <module>
	for key, value in hydrogen:
ValueError: too many values to unpack (expected 2)

Our code returns an error.

This is because each item in the “hydrogen” dictionary is a value. Keys and values are not two separate values in the dictionary.

We solve this error by using a method called items(). This method analyzes a dictionary and returns keys and values stored as tuples. Let’s add this method to our code:

for key, value in hydrogen.items():
	print("Key:", key)
	print("Value:", str(value))

Now, let’s try to run our code again:

Key: name
Value: Hydrogen
Key: atomic_weight
Value: 1.008
Key: atomic_number
Value: 1

We have added the items() method to the end of “hydrogen”. This returns our dictionary with key-value pairs stored as tuples. We can see this by printing out the contents of hydrogen.items() to the console:

Our code returns:

dict_items([('name', 'Hydrogen'), ('atomic_weight', 1.008), ('atomic_number', 1)])

Each key and value are stored in their own tuple.

A Note for Python 2.x

In Python 2.x, you use iteritems() in place of items(). This achieves the same result as we accomplished in the earlier example. The items() method is still accessible in Python 2.x. 

for key, value in hydrogen.iteritems():
	print("Key:", key)
	print("Value:", str(value))

Above, we use iteritems() instead of items(). Let’s run our code:

Key: name
Value: Hydrogen
Key: atomic_weight
Value: 1.008
Key: atomic_number
Value: 1

Our keys and values are unpacked from the “hydrogen” dictionary. This allows us to print each key and value to the console individually.

Python 2.x is starting to become deprecated. It is best to use more modern methods when available. This means items() is generally preferred over iteritems().

Example: Unpacking Values to a Variable

When you unpack a list to a variable, the number of variables to which you unpack the list items must be equal to the number of items in the list. Otherwise, an error is returned.

We have a list of floating-point numbers that stores the prices of donuts at a local donut store:

donuts = [2.00, 2.50, 2.30, 2.10, 2.20]

We unpack these values into their own variables. Each of these values corresponds to the following donuts sold by the store:

  • Raspberry jam
  • Double chocolate
  • Cream cheese
  • Blueberry

We unpack our list into four variables. This allows us to store each price in its own variable. Let’s unpack our list:

Venus profile photo

«Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!»

Venus, Software Engineer at Rockbot

raspberry_jam, double_chocolate, cream_cheese, blueberry = [2.00, 2.50, 2.30, 2.10, 2.20]
print(blueberry)

This code unpacks our list into four variables. Each variable corresponds with a different donut. We print out the value of “blueberry” to the console to check if our code works. Run our code and see what happens:

Traceback (most recent call last):
  File "main.py", line 1, in <module>
	raspberry_jam, double_chocolate, cream_cheese, blueberry = [2.00, 2.50, 2.30, 2.10, 2.20]
ValueError: too many values to unpack (expected 4)

We try to unpack four values, our list contains five values. Python does not know which values to assign to our variables because we are only unpacking four values. This results in an error.

The last value in our list is the price of the chocolate donut. We solve our error by specifying another variable to unpack the list:

raspberry_jam, double_chocolate, cream_cheese, blueberry, chocolate = [2.00, 2.50, 2.30, 2.10, 2.20]
print(blueberry)

Our code returns: 2.1. Our code successfully unpacks the values in our list.

Conclusion

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.

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!

Возможно, вам также будет интересно:

  • Valueerror i o operation on closed file csv почему ошибка
  • Valueerror dataframe constructor not properly called ошибка
  • Value too long in statement ошибка
  • Value does not fall within the expected range ошибка
  • Valorant ошибка установки лаунчера

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии