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?

  • The `d.values()` answers below are correct for your ordered input (assuming you have py >3.6 where dict (https://stackoverflow.com/questions/39980323/are-dictionaries-ordered-in-python-3-6/39980744) 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} ` – Demi-Lune Aug 27 '20 at 19:57

5 Answers5

1

Assuming your dictionary is called dict:

numpy_array = np.array([*dict.values()])
boi
  • 181
  • 1
  • 10
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. ])
hpaulj
  • 221,503
  • 14
  • 230
  • 353
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()))

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]
Ehsan
  • 12,072
  • 2
  • 20
  • 33
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])
Demi-Lune
  • 1,868
  • 2
  • 15
  • 26