How array comprehension with dict

Hi
I am very new to Numba. This is my first message.
I was wondering how I can integrate this python array comprehension with dict
to Numba.
xy_arr_1=[{'x':x_arr_1[i] , 'y':y_arr_1[i] } for i in range(0,len(x_arr_1)-1) ]

regards

Hey,

Welcome to Numba!

An important distinction to be made is if you want to create that list of dicts “outside” Numba, and pass it to a Numba-jitted function. Or do you want to create it from inside a jitted function?

The example below shows how to do the latter, it will return the typed Numba objects, a typed List containing typed Dicts:

from numba.typed import List
from numba import njit

@njit
def array_to_dicts(x, y):
    
    result = List()
    
    for i in range(0, len(x)-1):
        result.append({'x': x[i] , 'y': y[i] })

    return result

xdata = np.random.randn(5)
ydata = np.random.randn(5)

result = array_to_dicts(xdata, ydata)
result

This will return:

ListType[DictType[unicode_type,float64]<iv=None>]([
    {x: -0.6945678597313655, y: 0.40746183624111043}, 
    {x: -0.14963454032767076, y: -0.7699160744453164}, 
    {x: -0.43515355172163744, y: 0.5392491912918173},
    {x: 1.8492637284793418, y: -0.6743326606573761},
])

Note that the use of range(len(x)-1) in both your and my example will exclude the last element of the input array, if you need all elements to be included simply remove the -1.

This way of storing these x/y elements probably won’t give good performance compared to other structures, but it really depends on the use-case/context what would be best for you.

1 Like