I am getting the too many values to unpack
error. Any idea how I can fix this?
first_names = ['foo', 'bar']
last_names = ['gravy', 'snowman']
fields = {
'first_names': first_names,
'last_name': last_names,
}
for field, possible_values in fields: # error happens on this line
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.
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.
We can use the ** to unpack dictionaries and merge them in a new dict object. In the above example, we create a new dictionary by unpacking the contents of the previous dictionary in the new dictionary. We also have an operator to unpack elements from the list.
The items() method returns a view object that displays a list of dictionary's (key, value) tuple pairs.
Use items()
.
for field, possible_values in fields.items():
print(field, possible_values)
Use iteritems()
.
for field, possible_values in fields.iteritems():
print field, possible_values
See this answer for more information on iterating through dictionaries, such as using items()
, across Python versions.
For reference, iteritems()
was removed in Python 3.
For Python 3.x iteritems
has been removed. Use items instead.
for field, possible_values in fields.items():
print(field, possible_values)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With