简体   繁体   中英

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

Why Lists Can't Be Dictionary Keys

To be used as a dictionary key, an object must support the hash function (eg through hash ), equality comparison (eg 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'}

我不确定我们是否可以将numpy数组设置为dict键,但您可以使用下面的代码来交换disct键和值:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM