Karthikeyan Sise
Karthikeyan Sise

Reputation: 81

How to form dictionary with string and numpy array?

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'}

Upvotes: 1

Views: 1349

Answers (2)

DirtyBit
DirtyBit

Reputation: 16772

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'}

Upvotes: 3

Amit Nanaware
Amit Nanaware

Reputation: 3346

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()}

Upvotes: 0

Related Questions