Saturday, November 20, 2021

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

ItsMyCode |

If you get ValueError: too many values to unpack (expected 2), it means that you are trying to access too many values from an iterator. Value Error is a standard exception that can occur if the method receives an argument with the correct data type but an invalid value or if the value provided to the method falls outside the valid range.

In this article, let us look at what this error means and the scenarios you get this error and how to resolve the error with examples.

What is Unpacking in Python?

In Python, the function can return multiple values, and it can be stored in the variable. This is one of the unique features of Python when compared to other languages such as C++, Java, C# etc. 

Unpacking in Python is an operation where an iterable of values will be assigned to a tuple or list of variables.

Unpacking using List in Python

In this example, we are unpacking the list of elements where each element that we return from the list should assign to a variable on the left-hand side to store these elements.

x,y,z = [5,10,15]
print(x)
print(y)
print(z)

Output

5
10
15

Unpacking list using underscore

Underscoring is most commonly used to ignore values; when _ is used as a variable when we do not want to use this variable at a later point.

x,y,_ = [5,10,15]
print(x)
print(y)
print(_)

Output

5
10
15

Unpacking list using an asterisk

The drawback with an underscore is it can just hold one iterable value, but what if you have too many values that comes dynamically? Asterisk comes as a rescue over here. We can use the variable with an asterisk in front to unpack all the values that are not assigned, and it can hold all these elements in it.

x,y, *z = [5,10,15,20,25,30]
print(x)
print(y)
print(z)

Output

5
10
[15, 20, 25, 30]

What is ValueError: too many values to unpack (expected 2)?

ValueError: too many values to unpack (expected 2) occurs when there is a mismatch between the returned values and the number of variables. If you have more objects to assign and fewer variables to hold, you get a value error.

The error occurs mainly in 2 cases –

Scenario 1: Unpacking list

Let’s take a simple example that returns an iterable of three items instead of two, and we have two variables to hold these items on the left-hand side, and Python will throw ValueError: too many values to unpack.

Error Scenario

x,y =[5,10,15]

Output

Traceback (most recent call last):
  File "c:/Projects/Tryouts/main.py", line 1, in <module>
    x,y =[5,10,15]
ValueError: too many values to unpack (expected 2)

Solution

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

If you already know the number of elements in the list, then ensure you have an equal number of variables on the left-hand side to hold these elements to solve.

If you do not know the number of elements in the list or if your list is dynamic, then you can unpack the list with an asterisk operator. It will ensure that all the un-assigned elements will be stored in a single variable with an asterisk operator.

# In case we know the number of elements
# in the list to unpack
x,y,z =[5,10,15]
print("If we know the number of elements in list")
print(x)
print(y)
print(z)

# if the list is dynamic
a,b, *c = [5,10,15,20,25,30]
print("In case of dynamic list")
print(x)
print(y)
print(z)

Output

If we know the number of elements in list
5
10
15
In case of dynamic list
5
10
15

Scenario 2: Unpacking dictionary 

In Python, Dictionary is a set of unordered items which holds key-value pairs. Let us consider a simple example of an employee, which consists of three keys, and each holds a value, as shown below.

If we need to extract and print each of the key and value pairs in the employee dictionary, we can use iterate the dictionary elements using a for loop. 

Lets run our code and see what happens

Error Scenarios

# Unpacking using dictornary

employee= {
    "name":"Chandler",
    "age":25,
    "Salary":10000
}

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

Output

Traceback (most recent call last):
  File "c:/Projects/Tryouts/main.py", line 9, in <module>
    for keys, values in employee:
ValueError: too many values to unpack (expected 2)

Our code returns a Value Error.

We get a Value error in the above code because each item in the “employee” dictionary is a value. We should not consider the keys and values in the dictionary as two separate entities in Python.

Solution

We can resolve the error by using a method called items(). The items() function returns a view object which contains both key-value pairs stored as tuples.

# Unpacking using dictornary

employee= {
    "name":"Chandler",
    "age":25,
    "Salary":10000
}

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

Output

name Chandler
age 25
Salary 10000

Note: If you are using Python 2.x, you need to use iteritems() instead of the items() function. 

The post ValueError: too many values to unpack (expected 2) appeared first on ItsMyCode.



from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...