0

I have 4 NumPy arrays: a, b, c, d

I am running: {i: i.shape for i in [a,b,c,d]}

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    {i:i.shape for i in [a,b,c,d]}
  File "<stdin>", line 1, in <dictcomp>
    {i:i.shape for i in [a,b,c,d]}
TypeError: unhashable type: 'numpy.ndarray'

What am I doing wrong?

5
  • 2
    You're trying to make a numpy array as your dict key...you can't do that Commented Mar 28, 2018 at 18:02
  • I mean I want it to be "a": (10, 13), "b": (3,4,43) etc. Commented Mar 28, 2018 at 18:02
  • What do you really want to achieve? Commented Mar 28, 2018 at 18:23
  • @David a dict like you've produced in your answer that I have accepted! Commented Mar 28, 2018 at 18:39
  • Dictionary keys have to be immutable, unlike values which don't need to be. Commented Mar 28, 2018 at 18:51

4 Answers 4

4

Your code tries to make the numpy array as the key, rather than the variable name you are assigning the array to. Something like below would work

{i[1]: i[0].shape for i in [(a, "a"), (b, "b"), (c, "c") , (d, "d")]}
Sign up to request clarification or add additional context in comments.

1 Comment

Or: {name: locals()[name].shape for name in "abcd"}
4

You can't have a numpy array as a key. Try using something like:

{i:arr.shape for i,arr in enumerate([a,b,c,d])}

Comments

3

Another solution (just to give you options, as other people have already posted good ones):

{name: arr.shape for arr,name in zip([a,b,c,d],'abcd')}

Comments

1

You’re trying to use a numpy.ndarray as the key for your shape. This won’t work as the object isn’t hashable and you probably want to use something else as your key.

1 Comment

But how can I tell the dict to take "a", "b" ... as keys?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.