"'int' object is not iterable" iterating over a dict
Diez B. Roggisch
deets at nospam.web.de
Mon Oct 6 02:22:06 EDT 2008
mmiikkee13 schrieb:
>>>> 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
More information about the Python-list
mailing list