Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'too many values to unpack', iterating over a dict. key=>string, value=>list

Tags:

python

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
like image 298
tipu Avatar asked Mar 29 '11 00:03

tipu


People also ask

How do I fix too many values to unpack?

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.

What does too many values to unpack mean Python?

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.

How do I unpack 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.

What does .items do in Python?

The items() method returns a view object that displays a list of dictionary's (key, value) tuple pairs.


2 Answers

Python 3

Use items().

for field, possible_values in fields.items():
    print(field, possible_values)

Python 2

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.

like image 172
Philip Southam Avatar answered Oct 20 '22 18:10

Philip Southam


For Python 3.x iteritems has been removed. Use items instead.

for field, possible_values in fields.items():
    print(field, possible_values)
like image 88
Meistro Avatar answered Oct 20 '22 19:10

Meistro