Python用'numpy.ndarray'创建一个字典

时间:2013-03-03 17:14:25

标签: python arrays dictionary numpy runtime-error

我有一个空的'numpy.ndarray'

import numpy as np
my_grid =  np.zeros((5, 5))

parse = "max","min","avg"

我希望创建一个字典,其中每个解析元素都是“Key”

from collections import defaultdict

GridMetric = dict()
for arg in parse:
    GridMetric[arg].append(my_grid)

但我收到此错误

   Traceback (most recent call last):
  File "<editor selection>", line 3, in <module>
KeyError: 'max'

2 个答案:

答案 0 :(得分:3)

如果你想要的是一个字典,其键是名为parse的列表的不同元素,并且其值都是相同的数组,那么对代码的以下更改应该有效:

import numpy as np
my_grid =  np.zeros((5, 5))

parse = ["max","min","avg"]

d = {}
for arg in parse:
    d[arg] = my_grid

答案 1 :(得分:0)

尝试一下:

import numpy as np

my_grid =  np.zeros((5, 5))

parse = ["max","min","avg"]


for arg in parse:
    dict(parse=my_grid)

print(d)