0

The following code does not have any problem in Python 2.7, however in Python 3.4.3, throws TypeError: iteration over a 0-d array

import numpy as np
def c1():
        mat=[]
        mat.append(np.array(map(float,np.random.rand(7))))
        return mat
mylist=[]
mydict_={}
mydict_['dog']=c1()
mydict_['big']=c1()

justKeys={label:1 for label in list(mydict_.keys())}

for idx, word in enumerate(justKeys.keys()):
        mylist.append(np.array(map(float, mydict_[word][0])))

What should I do in order to the list mylist in both python2.7 and 3.4 get the same results?

2
  • my guess will be the .keys() as of blog.labix.org/2008/06/27/… Commented Jul 12, 2015 at 5:44
  • Thanks. Adding copy().keys() doesn't solve the problem. Commented Jul 12, 2015 at 5:51

1 Answer 1

2

The issue is not with the dictionary methods, but the map function, which is changed in Python 3 to return an iterator rather than a list. Numpy doesn't handle the iterators properly, so you need to add a list call to fix things:

def c1():
    mat=[]
    mat.append(np.array(list(map(float,np.random.rand(4,7)))))
    return mat

The rest of your code is a bit confusing, as you're creating a new dictionary, without any useful contents, then enumerating the keys of the new dictionary without using the indexes. It seems like you could just use my_list = [x[0] for x in dict_.values()] and have the same result (since the first item in the value lists is already a numpy array of floats, once you fix c1 as above).

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks gain. @Blckknght quick question: are mat.append(np.array(list(map(float,np.random.rand(7))))) and mat.append(np.random.rand(7)) same thing? I mean can be used interchangeably?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.