numpy:从(索引,值)字典创建数组

问题描述:

我有一个 dict 格式: {1:5,2:1,1,4:6,8:9}
,我想将其转换为以下形式的数组: [0,5,1,0,6,0,0,0,9]

因此,键表示数组的索引,而这些索引处的 dict 的值是

So the keys represent indexes into the array and the values of the dict at those indexes are the values of the array at the index.

是否有一种很好的快捷方式使用numpy做到这一点?

Is there a nice and quick way to do this with numpy?

就像 dict.get 一样简单。

>>> np.array([d.get(i, 0) for i in range(max(d) + 1)])
array([0, 5, 1, 0, 6, 0, 0, 0, 9])