How do I pass a dict to a numba function?

I have a python dict I want to use in a numba function. How can I pass it? This example gives the error:

TypingError: Failed in nopython mode pipeline (step: nopython frontend)
non-precise type pyobject
pyth_dict = {2: 2.3, 3: 1.3}

@numba.njit()
def foo(pyth_dict):
    x = pyth_dict[2]
    return 1

foo(pyth_dict)

How can I specify the type correctly?

Use a typed dict

Building on the above, one way to make sure that your dictionary is a numba typed dict is to declare it within a jitted function. For example, you could do

from numba import njit, typeof

@njit
def make_dict(keys, values):
  d = {}
  for i in range(len(keys)):
    d[keys[i]] = values[i]
  return d

pyth_dict = make_dict(np.array([2, 3], dtype=np.int64), np.array([2.3, 1.3], dtype=np.float64))

print(typeof(pyth_dict))

Then, when you call foo(pyth_dict), you obtain the expected result.

1 Like