The Python Oracle

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

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: A Thousand Exotic Places Looping v001

--

Chapters
00:00 'Too Many Values To Unpack', Iterating Over A Dict. Key=≫String, Value=≫List
00:24 Accepted Answer Score 602
00:49 Answer 2 Score 40
01:11 Answer 3 Score 89
01:24 Answer 4 Score 14
01:35 Thank you

--

Full question
https://stackoverflow.com/questions/5466...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python

#avk47



ACCEPTED ANSWER

Score 602


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.




ANSWER 2

Score 89


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

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



ANSWER 3

Score 40


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



ANSWER 4

Score 14


For lists, use enumerate

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

iteritems will not work for list objects