Bella
Bella

Reputation: 1017

How to assign each row in a numpy array into keys in dictionary python

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?

Upvotes: 1

Views: 1245

Answers (2)

Paul Panzer
Paul Panzer

Reputation: 53089

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.)

Upvotes: 2

Dani Mesejo
Dani Mesejo

Reputation: 61920

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}

Upvotes: 2

Related Questions