0

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?

2
  • don't use dict as variable name in python Commented Jan 25, 2021 at 8:22
  • you have to provide key 0, 1, or 2. Not the numpy array. You can iterate the numpy array and use the elements as key. Commented Jan 25, 2021 at 8:26

3 Answers 3

3

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]
Sign up to request clarification or add additional context in comments.

3 Comments

The second method works, but when I use the first method, I got TypeError: unhashable type: 'list'
@alryosha make you sure copied it correctly
Ah okay it's my mistake
1

Did you mean this?

    dict = {0 : 'red', 1 : 'blue', 2 : 'green'}
    label = np.array([0,0,0,1,1,1,2,2,2])
    for l in label:
        print(dict[l])

The output from this is: red red red blue blue blue green green green

Comments

1

You can use map. You need to iterate over label and take the corresponding value from the dictionary. Note:

  1. Don't use dict as a variable name in python
  2. I suppose you want to use np.array() not np.ndarray
d = {0 : 'red', 1 : 'blue', 2 : 'green'}
label = np.array([0,0,0,1,1,1,2,2,2])
output = list(map(lambda x: d[x], label))

output

['red', 'red', 'red', 'blue', 'blue', 'blue', 'green', 'green', 'green']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.