从字典创建一个 numpy 数组,其中包含包含索引元组的键



我有两个字典如下

o = {0: -0.0, 1: -0.0, 2: -0.0, 3: -0.0, 4: -0.0, 5: -0.0, 6: -0.0, 7: -0.0, 8: -0.0, 9: -0.0}

X = {(0, 0): 1.0, (0, 1): 0.0, (0, 2): 0.0, (1, 0): 0.0, (1, 1): 1.0, (1, 2): 0.0, (2, 0): 1.0, (2, 1): 0.0, (2, 2): 0.0}

我想创建 numpy 数组,以便字典中的键值对应于数组索引,值对应于值。

例如,在第二个字典的情况下,我的输出应该是

X = np.array([[1,0,0], [0,1,0], [1,0,0]])
import numpy as np
X = {(0, 0): 1.0, (0, 1): 0.0, (0, 2): 0.0, (1, 0): 0.0, (1, 1): 1.0, (1, 2): 0.0, (2, 0): 1.0, (2, 1): 0.0, (2, 2): 0.0}
result = np.zeros((3,3))
for key, val in X.items():
    result[key[0]][key[1]] = val
print (result)

输出:

[[1. 0. 0.]
 [0. 1. 0.]
 [1. 0. 0.]]

在这里,我为你写了一个小脚本,帮你解决所有字典

import numpy as np
def dict2arr(dictionary):
    # take all keys in dict
    l = list(dictionary.keys())
    # if result is 1D tensor
    if type(l[0])== int:
        result = np.zeros((len(dictionary)))
    # if result is nD tensor with n > 1
    else:
        # take the maximum shape, then plus 1 to generate correct shape
        shape = [i+1 for i in max(l)]
        result = np.zeros(shape)
    # just let the key is index and value is value of result
    for k,v in dictionary.items():
        result[k]=v
    return result

X 的结果:

array([[1., 0., 0.], [0., 1., 0.], [1., 0., 0.]])

结果为 o:

array([-0., -0., -0., -0., -0., -0., -0., -0., -0., -0.])

希望这是正确的解决方案!

最新更新