0

I have an object -> {0: 0.8, 1: 0.2, 2: 0, 3: 0}

I want to convert it to a numpy array, where the keys are the index, and the values are the values of the array -> [0.8, 0.2, 0, 0]

Whats the fastest and efficient way of doing this?

I am using a for loop, but is there a better way of doing this?

1
  • The d.values() answers below are correct for your ordered input (assuming you have py >3.6 where dict (stackoverflow.com/questions/39980323/…) gained insertion order). But is there a chance that your dict is input in a "wrong" order? For example d = {1:1.1, 2:2.2, 0: 0.8} Commented Aug 27, 2020 at 19:57

5 Answers 5

1

Assuming your dictionary is called dict:

numpy_array = np.array([*dict.values()])
Sign up to request clarification or add additional context in comments.

Comments

1

keys, items and values are the fastest way to get 'things' from a dict. Otherwise you have to iterate on the keys. A general approach that allows for skipped indices, and out-of-order ones:

In [81]: adict = {0: 0.8, 1: 0.2, 2: 0, 3: 0}                                                        
In [82]: keys = list(adict.keys())                                                                   
In [83]: arr = np.zeros(max(keys)+1)    # or set your own size                                                                 
In [84]: arr[keys] = list(adict.values())                                                            
In [85]: arr                                                                                         
Out[85]: array([0.8, 0.2, 0. , 0. ])

Comments

0

The above answer gives dict_values, but was in the right direction

the correct way to do it is:

d = {0: 0.8, 1: 0.2, 2: 0, 3: 0}
np_array = np.array(list(d.values()))

Comments

0

Dictionary is inherently orderless. You would need to sort your values according to your keys (assuming you do not have a missing key in your dictionary):

a = {0: 0.8, 1: 0.2, 2: 0, 3: 0}
np.array([i[1] for i in sorted(a.items(), key=lambda x:x[0])])

Another way of doing it is sorting in numpy:

b = np.array(list(a.items()))
b[b[:,0].argsort()][:,1]

output:

[0.8, 0.2, 0, 0]

Comments

0

A solution if input dict is not ordered or has missing values:

d = {1:1.1, 2:2.2, 0: 0.8, 4:4.4}
sz = 1+max(d.keys())   # or len(d) if you are sure there are no missing values 
x = np.full(sz, np.nan)
x[list(d.keys())] = list(d.values())
x
#array([0.8, 1.1, 2.2, nan, 4.4])

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.