Ask Your Question
0

TypeError: 'int' object is not iterable

asked 2012-07-03 13:03:11 +0100

MaelstromYamato gravatar image

Hello,

For a given matrix M (m by n) and vector V of size n, my goal is to do the following:

  1. Take the $\text{i}^{\text{th}}$ column of M and convert them as keywords for a dictionary and associate the keywords to the $\text{i}^{\text{th}}$ value of the vector V.
    1. I do (1) in MatVec(M,V) in the code below by creating a dictionary for each keyword and value. Finally I try to merge all the dictionaries.

Here is my code:

def DictionaryMerge(*args):
    import collections
    super_dict = collections.defaultdict(set)
    for d in args:
        for k, v in d.iteritmes():
            super_dict[k].add(v)
    return super_dict

def MatVec(M,V):
    from sets import Set
    Vec = V.list()
    MatCols = M.ncols()
    D2 = {}
    for i in range(MatCols):
        ColumnVec = M.column(i).list()
        CVec = list()
        for k in range(len(ColumnVec)):
            CVec.append(int(ColumnVec[k]))
        for j in CVec:
            dict = {j:Set(int(Vec[i]))}
            D2 = DictionaryMerge(dict,D2)
     return dict

M = matrix([[(i+1)*(j+2) for i in range(5)] for j in range(6)])
V = vector([int(i+100) for i in range(5)])
MatVec(M,V)

The error I get is:

Traceback (most recent call last):        return super_dict
  File "", line 1, in <module>

  File "/tmp/tmp4m6HiR/___code___.py", line 29, in <module>
     exec compile(u'MatVec(M,V)
  File "", line 1, in <module>

  File "/tmp/tmp4m6HiR/___code___.py", line 22, in MatVec
     dict = {j:Set(int(Vec[i]))}
  File "/home/usr111/sage/local/lib/python/sets.py", line 414, in __init__
     self._update(iterable)
  File "/home/usr111/sage/local/lib/python/sets.py", line 368, in _update
     for element in iterable:
 TypeError: 'int' object is not iterable

I am not so sure why I am getting this error.

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2012-07-03 14:04:42 +0100

benjaminfjones gravatar image

The problem is in the line

dict = {j:Set(int(Vec[i]))}

The Set constructor takes an iterable object and the python int type is not iterable. If you change the line to:

dict = {j:Set( [int(Vec[i])] )}

that problem should go away.

edit flag offensive delete link more

Comments

Oh boy... I feel silly how that stumped me all day long. Thank you!

MaelstromYamato gravatar imageMaelstromYamato ( 2012-07-03 18:19:51 +0100 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2012-07-03 13:03:11 +0100

Seen: 7,900 times

Last updated: Jul 03 '12