0

I have five key/value pairs in a python dict object:

dict1 = {0:3, 1:2, 2:2, 3:2, 4:3}

And I have a list of tuples:

list_of_tuples = [(0, 1), (0, 4), (2, 3)]

I want a numpy array of shape (5, 5, 2) that contains the value from the dict object for each tuple value. I get 5 from the number of keys in the dict object, and 2 from the number of values in each tuple.

That is:

  • at position (0, 1) of the numpy array, I want a numpy array with values (3, 2);
  • at position (0, 4) of the numpy array, I want a numpy array with values (3, 3);
  • at position (2, 3) of the numpy array, I want a numpy array with values (2, 2);
  • at all other positions of the numpy array, I want a numpy array with values (4, 4),

where I use (4, 4) as an indicator of an empty spot.

Is there a nice, Pythonic way of doing this?

1
  • 2
    Can you do this in some non-nice Pythonic way? You know, with ordinary dictionary access and indexing? Commented Feb 3, 2018 at 17:59

1 Answer 1

2

You can create an array of 4s using np.full and then populate it:

a = np.full((5, 5, 2), 4)
for x, y in list_of_tuples:
     a[x, y] = dict1[x], dict1[y]
Sign up to request clarification or add additional context in comments.

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.