"'int' object is not iterable" iterating over a dict

M

mmiikkee13

a_list = range(37)
list_as_dict = dict(zip(range(len(a_list)), [str(i) for i in a_list]))
for k, v in list_as_dict:
.... print k, v
....
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable

What 'int' object is this referring to? I'm iterating over a dict, not
an int.
 
D

Diez B. Roggisch

mmiikkee13 said:
a_list = range(37)
list_as_dict = dict(zip(range(len(a_list)), [str(i) for i in a_list]))
for k, v in list_as_dict:
... print k, v
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable

What 'int' object is this referring to? I'm iterating over a dict, not
an int.

Because

for name in dictionary:


will bind name to the *keys* of dictionary. Thus you end up with an int.

Then the tuple-unpacking occurs:

k, v = <number>

Which is equivalent to

k = <number>[0]
v = <number>[1]

And because <number> isn't iterable, it will fail.

Use

for k, v in dictionary.iteritems():


instead.

Diez
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top