0

This is a very simple task, but somehow, I can't seem to figure it out.

Let's say I have a dictionary

dictr = {(0,1,2): 0, (5,4,2):1} 

And an array:

A = [[0, 1, 2], [5, 4, 2]]

I am looking to get an array b = [0, 1]

I thought we could do it by:

B = np.vectorize(dictr.get)(A)

However, this is not working. Anyone knows why?

1
  • 1
    np.vectorize passes scalar elements of A to get, not pairs or tuples. Sometimes vectorize is convenient, but it does not help with speed. And often it is hard to use correctly. Commented Apr 8, 2020 at 18:07

2 Answers 2

1

The problem is that dictr.get is called for elements of A, not for A's rows. It calls dictr.get(A[0,0]), next dictr.get(A[0,1]), and so on. Each of elements of A is a scalar not present in the dictionary thus np.vectorize fallbacks to None. That is why you get 2x3 array of None.

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

Comments

0

It is because your dictionary keys are tuple, meanwhile the items in A are list. You should convert all the element inside A to tuple so the key may match

A python-ic way (without numpy) might seems like this (considering every item in A matches a key in dictr)

b = [dictr[tuple(item)] for item in A]

1 Comment

Remember that this code will produce error if there is an element in A which doesn't match with a key in dictr, so make sure to check it if you are not sure about the condition ;)

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.