valueerror: too many values to unpack (expected 2) – Code Example

Total
0
Shares

In this article I will provide you code examples to resolve valueerror: too many values to unpack (expected 2). This error clearly says that the value holding variables are not matching the total values.

Code Example

1. Unpacking in variables

first_value, second_value = ["foo", "bar", "baz"]

# Output
Traceback (most recent call last):
  File "/home/jdoodle.py", line 1, in <module>
    first_value, second_value = ["foo", "bar", "baz"]
ValueError: too many values to unpack (expected 2)

In the above code there was no variable available to hold the 3rd array value. In other words, unpacking of array was not possible because third array item is abandoned. So, Python threw too many values to unpack error.

Correct Code

first_value, second_value, third_value = ["foo", "bar", "baz"]

Also you can use pointer –

first_value, *second_value = ["foo", "bar", "baz", "faz", "fab"]

// Output
// first_value = "foo"
// second_value = ["bar", "baz", "faz", "fab"]

2. Unpacking in dictionary –

superhero = {
    "name": "Clark Kent",
    "alias": "Superman",
    "franchise": "dc"
}

for key, value in superhero:
    print("%s: %s" % (key, value))

If you run this code, you will get an error in output –

Traceback (most recent call last):
  File "/home/jdoodle.py", line 9, in <module>
    for key, value in superhero:
ValueError: too many values to unpack (expected 2)

This is because a dictionary considers key: value pair as key in loop. Now you have two options –

Correct Code 1 – Loop over key only

superhero = {
    "name": "Clark Kent",
    "alias": "Superman",
    "franchise": "dc"
}

for key in superhero:
    print("%s: %s" % (key, superhero[key]))

# Output
# name: Clark Kent
# alias: Superman
# franchise: dc

Correct Code 2 – Loop over key & value using .items() property

superhero = {
    "name": "Clark Kent",
    "alias": "Superman",
    "franchise": "dc"
}

for key, value in superhero.items():
    print("%s: %s" % (key, value))

# Output
# name: Clark Kent
# alias: Superman
# franchise: dc

Live Demo

Open Live Demo