【问题标题】:How to add numpy arrays as values in a dictionary of dictionaries?如何在字典字典中添加 numpy 数组作为值?
【发布时间】:2019-11-25 20:07:56
【问题描述】:

假设我有以下变量:

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

我是否必须创建一个新字典才能做到这一点?

【问题讨论】:

  • 有什么问题?听起来像是对字典键的正常迭代。作为值的数组与任何其他类型的对象没有什么不同。

标签: python numpy dictionary word2vec


【解决方案1】:

您可以将每个现有的 dict_dict 值(当前是元组)替换为通过 Python dict 理解创建的新 dicts。例如:

for key in dict_dict.keys():
    words = dict_dict[key]
    subdict = { word : wv[word] for word in words}
    dict_dict[key] = subdict

【讨论】:

  • 这正是我想要的!我不知道如何将其形式化,所以这很有帮助!
  • 不客气!也可以作为具有 nested 理解的 1-liner,没有明确的 for 循环和本地变量,但上面更清楚。 (1-liner 将是:dict_dict = { k : { word : wv[word] for word in dict_dict[k]} for k, v in dict_dict.items() }。)
猜你喜欢
  • 2018-04-22
  • 2018-04-25
  • 1970-01-01
  • 1970-01-01
  • 2021-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-22
相关资源
最近更新 更多