如何在字典的字典中添加 numpy 数组作为值?
How to add numpy arrays as values in a dictionary of dictionaries?
假设我有以下变量:
import gensim
from gensim.models import KeyedVectors
wv = KeyedVectors.load_word2vec_format('GoogleNews-vectors-negative300.bin', binary=True)
dict_dict = {
"abc": ('dog', 'cat', 'bat'),
"def": ('fat', 'hat', 'rat')
}
在这种情况下,wv
是一个word2vec模型。
我想获取 dict_dict
中每个键的值,提取值的向量 (e.g. wv['dog']
),并让该值现在充当子字典的键:
dict_dict = {
"abc": ({'dog': array([ 5.12695312e-02, -2.23388672e-02, -1.72851562e-01, 1.61132812e-01]), {'cat':array([ 5.12695312e-02, -2.23388672e-02, -1.72851562e-01, 1.61132812e-01]), array([ 5.12695312e-02, -2.23388672e-02, -1.72851562e-01, 1.61132812e-01]):'bat')}
我是否必须创建一个新词典才能执行此操作?
您可以将每个现有的 dict_dict
值(目前是元组)替换为通过 Python 字典理解创建的新字典。例如:
for key in dict_dict.keys():
words = dict_dict[key]
subdict = { word : wv[word] for word in words}
dict_dict[key] = subdict
假设我有以下变量:
import gensim
from gensim.models import KeyedVectors
wv = KeyedVectors.load_word2vec_format('GoogleNews-vectors-negative300.bin', binary=True)
dict_dict = {
"abc": ('dog', 'cat', 'bat'),
"def": ('fat', 'hat', 'rat')
}
在这种情况下,wv
是一个word2vec模型。
我想获取 dict_dict
中每个键的值,提取值的向量 (e.g. wv['dog']
),并让该值现在充当子字典的键:
dict_dict = {
"abc": ({'dog': array([ 5.12695312e-02, -2.23388672e-02, -1.72851562e-01, 1.61132812e-01]), {'cat':array([ 5.12695312e-02, -2.23388672e-02, -1.72851562e-01, 1.61132812e-01]), array([ 5.12695312e-02, -2.23388672e-02, -1.72851562e-01, 1.61132812e-01]):'bat')}
我是否必须创建一个新词典才能执行此操作?
您可以将每个现有的 dict_dict
值(目前是元组)替换为通过 Python 字典理解创建的新字典。例如:
for key in dict_dict.keys():
words = dict_dict[key]
subdict = { word : wv[word] for word in words}
dict_dict[key] = subdict