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.

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

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!

In this article, we will walk you through the ways to solve the ValueError: Too Many Values to Unpack Error in Python. Let us discuss the possible causes of this error and the corresponding fixes.

Table of Contents

  1. ValueError: Too Many Values to Unpack Error in Python
  2. Assignment of Iterable Values to Variables and ValueError in Python
  3. ValueError: Too Many Values to Unpack While Iterating Dictionary in Python
  4. Function Return Values and ValueError in Python
  5. To Sum It Up
  6. Donate to Avid Python

The ValueError: Too Many Values to Unpack Error in Python is often encountered while unpacking an iterable. Say, you have a python list with three items. Now, you want to assign the three items of the list to separate variables.

How many variables would you need? Three of course!

Consider the following example. There is a list called deserts with 3 items and we assign them to 3 variables, one, two, and three respectively.

You can see the difference in output on printing the entire list and the individual variables.

deserts = ["Vanilla", "Chocolate", "Fudge"]
print(deserts)             
one, two, three =  deserts 
print(one)                 
print(two)
print(three)

Output

['Vanilla', 'Chocolate', 'Fudge']
Vanilla
Chocolate
Fudge

This is essentially what unpacking means; assignment of values of an iterable to individual variables. It is also referred to as retrieving items from an iterable.

If the number of python variables will be any less than three, then you will get the ValueError: too many values to unpack error. This happens because when the number of variables is not equal to the number of values to be unpacked, Python is confused as to what to assign to which variable and what to leave out.

Let us discuss the various scenarios that might lead to the occurrence of a ValueError: Too Many Values to Unpack Error in Python.

Assignment of Iterable Values to Variables and ValueError in Python

Let us begin with the most basic cause of ValueError: Too Many Values to Unpack Error in Python. As we have already seen previously in an example, to unpack an iterable to variables, the number of variables should be equal to the number of items present in the iterable.

If this is not the case, then we get the ValueError: Too Many Values to Unpack Error in Python. Note that the iterable could be anything starting from a string to a python tuple, a list, a set, or a dictionary.

Consider the following example.

We have a list called length that has 5 integer values. To unpack this list, we need 5 variables. But as you can see, we only have 4 variables, a, b, c, and d.

Therefore in the output, we get the ValueError exception. This happens because Python gets confused with what value to assign to which variable since the number of values and variables is unequal.

length = [1, 4, 2, 5, 6]
a, b, c, d = length
print("We get an error")

Output

Traceback (most recent call last):
  File "<string>", line 2, in <module>
ValueError: too many values to unpack (expected 4)

To solve this issue, we should put one more variable on the left side.

length = [1, 4, 2, 5, 6]
a, b, c, d, e = length
print("The error is resolved")

Output

The error is resolved

You can also use an underscore(_) as a placeholder to discard and leave out a value as shown below:

length = [1, 4, 2, 5, 6]
a, b, c, d, _ = length
print("Leave out the last value, 6")

Output

Leave out the last value, 6

ValueError: Too Many Values to Unpack While Iterating Dictionary in Python

A dictionary in Python consists of key-value pairs. Iterating over these pairs is quite confusing at times and may lead to the occurrence of “ValueError: Too Many Values to Unpack” error.

Consider the code given below.

desert = {
    "flavor":"Cherry",
    "colour":"Red",
    "quantity":2
}
for k, v in desert:
    print("The attributes: ", k)
    print("The values: ", str(v))

Output:

Traceback (most recent call last):
  File "<string>", line 6, in <module>
ValueError: too many values to unpack (expected 2)

Here, we first define a dictionary, desert with 3 key-value pairs. Then, we use a for loop to iterate over this dictionary and print the key-value pairs. We can also say that we are unpacking the dictionary desert into two variables: k and v.

When you run the code, you will get the “ValueError: Too Many Values to Unpack” error. This happens because we assume the keys and values as separate entities in the dictionary which is not true while we are unpacking a dictionary. In fact, the entire key-value pair of the dictionary is a single item.

To solve this issue, we should use the items() method. This method treats the key-value pairs as one whole entity and thus the error in unpacking is resolved.

desert = {
    "flavor":"Cherry",
    "colour":"Red",
    "quantity":2
}
for k, v in desert.items():
    print("The attribute : ", k)
    print("The value     : ", str(v))

Output

The attribute :  flavor
The value     :  Cherry
The attribute :  colour
The value     :  Red
The attribute :  quantity
The value     :  2

You can see that we just added the items() method on line 6 and this time we get the desired output.

Note that in Python 2.x, in place of the items() method, we use the iteritems() method.

Function Return Values and ValueError in Python

We know that when we create a function in Python, we also need to have some variables to store the values that will be returned by the function. Look at this example.

You can see that we have a function price that calculates the cost of two items. This function returns a single value, which is the total price to be paid.

Now, to receive this value, we must define a variable while calling the function. Here, this variable is total as you can see in line 5.

def price(pie, custard):
    cost = pie + custard
    return cost

total = price(100, 75)
print("Payable amount: ", total)

Output

Payable amount:  175

Now let us change our code a bit. We also want to add some tax to the cost and update the customer about it.

You can see that this time, we return 3 values: cost, tax, and total_amount. To receive these values, we need 3 variables which here are x, y, and z respectively.

def price(pie, custard):
    cost = pie + custard
    tax = 50
    total_amount = cost + tax
    return cost, tax, total_amount 

x, y, z = price(100, 75)

print("Item total: ", x)
print("Tax added : ", y)
print("Pay this  : ", z)

Output

Item total:  175
Tax added :  50
Pay this  :  225

But wonder what will happen if the number of values returned is not equal to the number of variables declared to receive them? See this time, we declare only 2 variables.

x, y = price(100, 75)

Output

Traceback (most recent call last):
  File "<string>", line 7, in <module>
ValueError: too many values to unpack (expected 2)

You can see that now we get the “ValueError: Too Many Values to Unpack” error because the number of values returned by the function is 3 while the number of variables to receive those values is only 2.

When you work with functions, it is important to declare as many variables while calling the function as there will be the number of values returned.

However, if you assign a single variable to receive multiple values, it will work fine as it acts as a python tuple.

def price(pie, custard):
    cost = pie + custard
    tax = 50
    total_amount = cost + tax
    return cost, tax, total_amount 

x = price(100, 75)
print(x)

Output

(175, 50, 225)

The output we get on printing x is a tuple of all the values returned by the function.

To Sum It Up

In this article, we learned about the “ValueError: Too Many Values to Unpack” Error in Python. We saw the various reasons that cause this error along with the corresponding solutions. We discussed how to avoid getting the “ValueError: Too Many Values to Unpack” Error while unpacking a list, iterating over a dictionary, and returning values from a function.

To learn more about python programming, you can read this article on python simplehttpserver. You might also like this article on try-except vs if else.

This is it for this article. Keep coding!

Donate to Avid Python

Dear reader,
If you found this article helpful and informative, I would greatly appreciate your support in keeping this blog running by making a donation. Your contributions help us continue creating valuable content for you and others who come across my blog. 
No matter how big or small, every donation is a way of saying "thank you" and shows that you value the time and effort we put into writing these articles. If you feel that our article has provided value to you, We would be grateful for any amount you choose to donate. 
Thank you for your support! 
Best regards, 
Aditya
Founder

If you want to Pay Using UPI, you can also scan the following QR code.

Payment QR Code

Payment QR Code

Понравилась статья? Поделить с друзьями:
  • Too many redirects ошибка wordpress
  • Too many redirections вконтакте ошибка
  • Too many levels of symbolic links ошибка
  • Tomzn tovpd3 63va ошибка ud
  • Tomb raider ошибка при распаковки unarc dll