Too many values to unpack expected 2 python как исправить

На чтение 5 мин Просмотров 18.5к. Опубликовано 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 », разобрались в причинах и механизме ее возникновения. Мы также увидели, что этой ошибки можно избежать.

This problem looked familiar so I thought I’d see if I could replicate from the limited amount of information.

A quick search turned up an entry in James Bennett’s blog here which mentions that when working with the UserProfile to extend the User model a common mistake in settings.py can cause Django to throw this error.

To quote the blog entry:

The value of the setting is not «appname.models.modelname», it’s just «appname.modelname». The reason is that Django is not using this to do a direct import; instead, it’s using an internal model-loading function which only wants the name of the app and the name of the model. Trying to do things like «appname.models.modelname» or «projectname.appname.models.modelname» in the AUTH_PROFILE_MODULE setting will cause Django to blow up with the dreaded «too many values to unpack» error, so make sure you’ve put «appname.modelname», and nothing else, in the value of AUTH_PROFILE_MODULE.

If the OP had copied more of the traceback I would expect to see something like the one below which I was able to duplicate by adding «models» to my AUTH_PROFILE_MODULE setting.

TemplateSyntaxError at /

Caught an exception while rendering: too many values to unpack

Original Traceback (most recent call last):
  File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/template/debug.py", line 71, in render_node
    result = node.render(context)
  File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/template/debug.py", line 87, in render
    output = force_unicode(self.filter_expression.resolve(context))
  File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/template/__init__.py", line 535, in resolve
    obj = self.var.resolve(context)
  File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/template/__init__.py", line 676, in resolve
    value = self._resolve_lookup(context)
  File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/template/__init__.py", line 711, in _resolve_lookup
    current = current()
  File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/contrib/auth/models.py", line 291, in get_profile
    app_label, model_name = settings.AUTH_PROFILE_MODULE.split('.')
ValueError: too many values to unpack

This I think is one of the few cases where Django still has a bit of import magic that tends to cause confusion when a small error doesn’t throw the expected exception.

You can see at the end of the traceback that I posted how using anything other than the form «appname.modelname» for the AUTH_PROFILE_MODULE would cause the line «app_label, model_name = settings.AUTH_PROFILE_MODULE.split(‘.’)» to throw the «too many values to unpack» error.

I’m 99% sure that this was the original problem encountered here.

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.

The error “too many values to unpack” is common in Python, you might have seen it while working with lists.

The Python error “too many values to unpack” occurs when you try to extract a number of values from a data structure into variables that don’t match the number of values. For example, if you try to unpack the elements of a list into variables whose number doesn’t match the number of elements in the list.

We will look together at some scenarios in which this error occurs, for example when unpacking lists, dictionaries or when calling Python functions.

By the end of this tutorial you will know how to fix this error if you happen to see it.

Let’s get started!

How Do You Fix the Too Many Values to Unpack Error in Python

What causes the too many values to unpack error?

This happens, for example, when you try to unpack values from a list.

Let’s see a simple example:

>>> week_days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
>>> day1, day2, day3 = week_days

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 3)

The error complains about the fact that the values on the right side of the expression are too many to be assigned to the variables day1, day2 and day3.

As you can see from the traceback this is an error of type ValueError.

So, what can we do?

One option could be to use a number of variables on the left that matches the number of values to unpack, in this case seven:

>>> day1, day2, day3, day4, day5, day6, day7 = week_days
>>> day1
'Monday'
>>> day5
'Friday'

This time there’s no error and each variable has one of the values inside the week_days array.

In this example the error was raised because we had too many values to assign to the variables in our expression.

Let’s see what happens if we don’t have enough values to assign to variables:

>>> weekend_days = ['Saturday' , 'Sunday']
>>> day1, day2, day3 = weekend_days

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: not enough values to unpack (expected 3, got 2)

This time we only have two values and we are trying to assign them to the three variables day1, day2 and day3.

That’s why the error says that it’s expecting 3 values but it only got 2.

In this case the correct expression would be:

>>> day1, day2 = weekend_days

Makes sense?

Another Error When Calling a Python Function

The same error can occur when you call a Python function incorrectly.

I will define a simple function that takes a number as input, x, and returns as output two numbers, the square and the cube of x.

>>> def getSquareAndCube(x):
        return x**2, x**3 
>>> square, cube = getSquareAndCube(2)
>>> square
4
>>> cube
8

What happens if, by mistake, I assign the values returned by the function to three variables instead of two?

>>> square, cube, other = getSquareAndCube(2)

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: not enough values to unpack (expected 3, got 2)

We see the error “not enough values to unpack” because the value to unpack are two but the variables on the left side of the expression are three.

And what if I assign the output of the function to a single variable?

>>> output = getSquareAndCube(2)
>>> output
(4, 8)

Everything works well and Python makes the ouput variable a tuple that contains both values returned by the getSquareAndCube function.

Too Many Values to Unpack With the Input Function

Another common scenario in which this error can occur is when you use the Python input() function to ask users to provide inputs.

The Python input() function reads the input from the user and it converts it into a string before returning it.

Here’s a simple example:

>>> name, surname = input("Enter your name and surname: ")
Enter your name and surname: Claudio Sabato

Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    name, surname = input("Enter your name and surname: ")
ValueError: too many values to unpack (expected 2)

Wait a minute, what’s happening here?

Why Python is complaining about too many values to unpack?

That’s because the input() function converts the input into a string, in this case “Claudio Sabato”, and then it tries to assign each character of the string to the variables on the left.

So we have multiple characters on the right part of the expression being assigned to two variables, that’s why Python is saying that it expects two values.

What can we do about it?

We can apply the string method split() to the ouput of the input function:

>>> name, surname = input("Enter your name and surname: ").split()
Enter your name and surname: Claudio Sabato
>>> name
'Claudio'
>>> surname
'Sabato'

The split method converts the string returned by the input function into a list of strings and the two elements of the list get assigned to the variables name and surname.

By default, the split method uses the space as separator. If you want to use a different separator you can pass it as first parameter to the split method.

Using Maxsplit to Solve This Python Error

There is also another way to solve the problem we have observed while unpacking the values of a list.

Let’s start again from the following code:

>>> name, surname = input("Enter your name and surname: ").split()

This time I will provide a different string to the input function:

Enter your name and surname: Mr John Smith

Traceback (most recent call last):
  File "<pyshell#29>", line 1, in <module>
    name, surname = input("Enter your name and surname: ").split()
ValueError: too many values to unpack (expected 2)

In a similar way as we have seen before, this error occurs because split converts the input string into a list of three elements. And three elements cannot be assigned to two variables.

There’s a way to tell Python to split the string returned by the input function into a number of values that matches the number of variables, in this case two.

Here is the generic syntax for the split method that allows to do that:

<string>.split(separator, maxsplit)

The maxsplit parameter defines the maximum number of splits to be used by the Python split method when converting a string into a list. Maxsplit is an optional parameter.

So, in our case, let’s see what happens if we set maxsplit to 1.

>>> name, surname = input("Enter your name and surname: ").split(' ', 1)

Enter your name and surname: Mr John Smith
>>> name
'Mr'
>>> surname
'John Smith'

The error is gone, the logic of this line is not perfect considering that surname is ‘John Smith’. But this is just an example to show how maxsplit works.

So, why are we setting maxsplit to 1?

Because in this way the string returned by the input function is only split once when being converted into a list, this means the result is a list with two elements (matching the two variables on the left of our expression).

Too Many Values to Unpack with Python Dictionary

In the last example we will use a Python dictionary to explain another common error that shows up while developing.

I have created a simple program to print every key and value in the users dictionary:

users = {
    'username' : 'codefather',
    'name' : 'Claudio',
}

for key, value in users:
    print(key, value)

When I run it I see the following error:

$ python dict_example.py

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

Where is the problem?

Let’s try to execute a for loop using just one variable:

for user in users:
    print(user)

The output is:

$ python dict_example.py
username
name

So…

When we loop through a dictionary using its name we get back just the keys.

That’s why we were seeing an error before, we were trying to unpack each key into two variables: key and value.

To retrieve each key and value from a dictionary we need to use the dictionary items() method.

Let’s run the following:

for user in users.items():
    print(user)

This time the output is:

('username', 'codefather')
('name', 'Claudio')

At every iteration of the for loop we get back a tuple that contains a key and its value. This is definitely something we can assign to the two variables we were using before.

So, our program becomes:

users = {
    'username' : 'codefather',
    'name' : 'Claudio',
}

for key, value in users.items():
    print(key, value)

The program prints the following output:

$ python dict_example.py
username codefather
name Claudio

All good, the error is fixed!

Conclusion

We have seen few examples that show when the error “too many values to unpack” occurs and how to fix this Python error.

In one of the examples we have also seen the error “not enough values to unpack”.

Both errors are caused by the fact that we are trying to assign a number of values that don’t match the number of variables we assign them to.

And you? Where are you seeing this error?

Let me know in the comments below 🙂

I have also created a Python program that will help you go through the steps in this tutorial. You can download the source code here.

Claudio Sabato - Codefather - Software Engineer and Programming Coach

I’m a Software Engineer and Programming Coach. I want to help you in your journey to become a Super Developer!

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!

Понравилась статья? Поделить с друзьями:
  • Как найти сумку сахарову
  • Энергетический уровень элементов как найти
  • Как найти координату вершины четырехугольника
  • Как в одноклассниках найти человека по фио
  • Как найти свой город мечты