Josh
Josh

Reputation: 12791

Unpacking dictionaries of lists

The following fails in Python 3.5:

for key, (a, b) in {'my_key': ('foo', 'bar')}:
  print(key, a, b)

with:

ValueError: too many values to unpack (expected 2)

Why is it unable to unpack the tuple properly?

Upvotes: 1

Views: 56

Answers (1)

arewm
arewm

Reputation: 649

If you use the items() method on the dictionary, it will work.

>>> for key, (a,b) in {'my_key': ('foo','bar')}.items():
...     print(key, a, b)
...
my_key foo bar

See: Iterating over dictionaries using 'for' loops

Upvotes: 2

Related Questions