Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
88 views
in Technique[技术] by (71.8m points)

python - dictionary indexing with numpy array

I have

dict = {0 : 'red', 1 : 'blue', 2 : 'green'}
label = np.ndarray([0,0,0,1,1,1,2,2,2])

As I want to get value corresponding to key by using label, I called

dict[label]

But I got

TypeError: unhashable type: 'numpy.ndarray'

How can I solve it?

question from:https://stackoverflow.com/questions/65881130/dictionary-indexing-with-numpy-array

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Unfortunately it's not quite as easy as that, but there are simple alternatives.
you can either have your "dict" (you shouldn't use reserved names) as an array as well:

my_dict = np.array(['red', 'blue', 'green'])
label = np.array([0,0,0,1,1,1,2,2,2])
my_dict[[label]]

or you can use a comprehension:

[dict[item] for item in label]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...