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

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • mmiikkee13

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

    >>a_list = range(37)
    >>list_as_dic t = 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.
  • Alex_Gaynor

    #2
    Re: &quot;'int' object is not iterable&quot; iterating over a dict

    On Oct 5, 8:11 pm, mmiikkee13 <mmiikke...@gma il.comwrote:
    >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.
    It thinks you are trying to unpack the first item, you mean to be
    doing for k, v in list_as_dict.it eritems()

    Comment

    • Diez B. Roggisch

      #3
      Re: &quot;'int' object is not iterable&quot; iterating over a dict

      mmiikkee13 schrieb:
      >>>a_list = range(37)
      >>>list_as_di ct = 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 <numberisn't iterable, it will fail.

      Use

      for k, v in dictionary.iter items():


      instead.

      Diez

      Comment

      Working...