1

How to interchange key-value pair of my dict where key is string and value is numpy array

word2index = {'think': array([[9.56090081e-05]]), 
              'apple':array([[0.00024469]])}

Now I need output like this

index2word = {array([[9.56090081e-05]]):'think', 
              array([[0.00024469]]):'apple'}
4
  • 2
    Not a good idea to have a list of array as a key in the dict. Commented Apr 2, 2019 at 9:30
  • Why Lists Can't Be Dictionary Keys in Python Commented Apr 2, 2019 at 9:35
  • 1
    You can't use mutables (such as numpy arrays) as dictionary keys. Commented Apr 2, 2019 at 9:38
  • @Sisekarthikeyan, you may consider accepting an answer that helped: meta.stackexchange.com/questions/5234/… cheers Commented Apr 9, 2019 at 12:01

2 Answers 2

3

Why Lists Can't Be Dictionary Keys

To be used as a dictionary key, an object must support the hash function (e.g. through hash), equality comparison (e.g. through eq or cmp)

That said, the simple answer to why lists cannot be used as dictionary keys is that lists do not provide a valid hash method.

However, using a string representation of the list:

word2index = {'think': [9.56090081e-05], 'apple': [0.00024469]}
print({repr(v):k for k,v in word2index.items()})

OUTPUT:

{'[9.56090081e-05]': 'think', '[0.00024469]': 'apple'}

OR:

Converting the list to a tuple:

print({tuple(v):k for k,v in word2index.items()})

OUTPUT:

{(9.56090081e-05,): 'think', (0.00024469,): 'apple'}
Sign up to request clarification or add additional context in comments.

1 Comment

Agree for both solutions.
0

I am not sure if we can set numpy array as dict key, but you can use below code to interchange the disct key and values:

index2word = {value:key for key, value in word2index.items()}

Comments

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.