使用包含索引元组的键从字典创建numpy数组

时间:2019-07-15 09:01:24

标签: python-3.x numpy dictionary

我有两个字典如下

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]])

2 个答案:

答案 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.]]

答案 1 :(得分: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.])

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