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

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              

This question is related to python

The answer is


you are missing fields.iteritems() in your code.

You could also do it other way, where you get values using keys in the dictionary.

for key in fields:
    value = fields[key]

You want to use iteritems. This returns an iterator over the dictionary, which gives you a tuple(key, value)

>>> for field, values in fields.iteritems():
...     print field, values
... 
first_names ['foo', 'bar']
last_name ['gravy', 'snowman']

Your problem was that you were looping over fields, which returns the keys of the dictionary.

>>> for field in fields:
...     print field
... 
first_names
last_name

data = (['President','George','Bush','is','.'],['O','B-PERSON','I-PERSON','O','O'])
corpus = []
for(doc,tags) in data:
    doc_tag = []
    for word,tag in zip(doc,tags):
        doc_tag.append((word,tag))
        corpus.append(doc_tag)
        print(corpus)

For lists, use enumerate

for field, possible_values in enumerate(fields):
    print(field, possible_values)

iteritems will not work for list objects


Can't be iterating directly in dictionary. So you can through converting into tuple.

first_names = ['foo', 'bar']
last_names = ['gravy', 'snowman']

fields = {
    'first_names': first_names,
    'last_name': last_names,
         } 
tup_field=tuple(fields.items())
for names in fields.items():
     field,possible_values = names
     tup_possible_values=tuple(possible_values)
     for pvalue in tup_possible_values:
           print (field + "is" + pvalue)

In Python3 iteritems() is no longer supported

Use .items

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

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

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