1

I have a rather large numpy array. I'd like to take each row in my array and assign it to be a key in a dictionary I created. For example, I have a short 2-dimensional array:

my_array = [[5.8 2.7 3.9 1.2]
            [5.6 3.  4.5 1.5]
            [5.6 3.  4.1 1.3]]

and I'd like to create a dictionary that each row is a key, with empty values (later I plan to add values dynamically), like so:

my_dict = {[5.8 2.7 3.9 1.2]:,
            [5.6 3.  4.5 1.5]:,
            [5.6 3.  4.1 1.3]:}

How can I do it?

3
  • You cannot have a numpy array as the key of a dictionary Commented Oct 3, 2019 at 20:07
  • I can do it if I convert the rows into tuples, but then how do I do it? Commented Oct 3, 2019 at 20:10
  • 1
    Why do you want to do this? Surely there is a better way to do what you are trying to do. This screams XY problem. Commented Oct 3, 2019 at 20:13

2 Answers 2

2

If a tuple will do, then:

import numpy as np

my_array = np.array([[5.8, 2.7, 3.9, 1.2],
                     [5.6, 3., 4.5, 1.5],
                     [5.6, 3., 4.1, 1.3]])


d = { k : None for k in map(tuple, my_array)}

print(d)

Output

{(5.8, 2.7, 3.9, 1.2): None, (5.6, 3.0, 4.5, 1.5): None, (5.6, 3.0, 4.1, 1.3): None}

As an alternative, you could do:

d = { tuple(row) : None for row in my_array}
Sign up to request clarification or add additional context in comments.

Comments

2

You'll have to put some placeholder for the values, None is often used to mean nothing. You also need to convert the rows to something hashable; tuples are the obvious choice.

my_array = np.arange(15).reshape(3,5)

import numpy.lib.recfunctions as nlr

dict.fromkeys(nlr.unstructured_to_structured(my_array).tolist())
# {(0, 1, 2, 3, 4): None, (5, 6, 7, 8, 9): None, (10, 11, 12, 13, 14): None}

unstructured_to_structured is a little trick that lumps each row of my_array together using a compund dtype. tolist converts these compound elements to tuples.

If you would prefer a different placeholder instead of None you can specify that as the second argument to dict.fromkeys. (Do not use a mutable placeholder because all the values will be references to the same object.)

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.