Gianni Spear
Gianni Spear

Reputation: 7958

Python create a dictionary with 'numpy.ndarray'

I have an empty 'numpy.ndarray'

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

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

I wish to create a dictionary where each element of parse is the "Key"

from collections import defaultdict

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

but i get this error

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

Upvotes: 1

Views: 11846

Answers (2)

Muhammad Umar
Muhammad Umar

Reputation: 11

Try this:

import numpy as np

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

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


for arg in parse:
    dict(parse=my_grid)

print(d)

Upvotes: 1

ASGM
ASGM

Reputation: 11391

If what you want is a dictionary whose keys are the different elements of the list called parse and whose values are all the same array, then the following changes to your code should work:

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

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

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

Upvotes: 3

Related Questions