'How to declare a typed Dict whose value is a Nested list in numba
I know that numba has a numba.typed.Dict which is a typed dict, but my dict's value is a list of lists, each key in the dict may have different length of the outer list; also each inner list may have different lengths too; the type of the inner list is A pair of float32 though. I am wondering does numba support such kind of structure and how to declare it?
An example of the dictionary is below
{
“Seattle”: [[[1.2, 3.5], [4.5, 6.7]]],
“New York”:[ [[5.7, 22.4], [3.5, 7.8], [6.9, 4.1]], [[2.3, 4.5]]],
“Boston”: [[[2.4, 5.0]]]
}
region_polygons = Dict.empty(
key_type=types.unicode_type,
value_type= <------ try to figure out this )
Solution 1:[1]
We can take advantage of Typed Lists which support nesting. I am using List(lsttype=...) to manually specify the type which the official docs unfortunately do not show, but bear in mind that Typed Lists are currently an experimental feature (v 0.47) and may be subject to change in later releases.
>>> from numba.typed import Dict, List
>>> from numba.types import float32, unicode_type, ListType
>>> py_dct = {
... "Seattle": [[[1.2, 3.5], [4.5, 6.7]]],
... "New York":[ [[5.7, 22.4], [3.5, 7.8], [6.9, 4.1]], [[2.3, 4.5]]],
... "Boston": [[[2.4, 5.0]]]
... }
>>> nested_3 = ListType(ListType(ListType(float32)))
>>> nested_2 = ListType(ListType(float32))
>>> nested_1 = ListType(float32)
>>> nb_dct = Dict.empty(
... key_type=unicode_type,
... value_type=nested_3,
... )
>>> for city, lst in py_dct.items():
... out_lst = List(lsttype=nested_3)
... for outer in lst:
... mid_lst = List(lsttype=nested_2)
... for middle in outer:
... in_lst = List(lsttype=nested_1)
... for inner in middle:
... in_lst.append(inner)
... mid_lst.append(in_lst)
... out_lst.append(mid_lst)
... nb_dct[city] = out_lst
>>> nb_dct['Seattle']
ListType[ListType[ListType[float32]]]([[[1.2000000476837158, 3.5], [4.5, 6.699999809265137]]])
>>> nb_dct['New York']
ListType[ListType[ListType[float32]]]([[[5.699999809265137, 22.399999618530273], [3.5, 7.800000190734863], [6.900000095367432, 4.099999904632568]], [[2.299999952316284, 4.5]]])
>>> nb_dct['Boston']
ListType[ListType[ListType[float32]]]([[[2.4000000953674316, 5.0]]])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Matt Eding |
