【问题标题】:Dict_values' object does not support indexingDict_values 的对象不支持索引
【发布时间】:2016-11-28 21:49:18
【问题描述】:

以下是我的代码:

word_centroid_map =dict(zip(model.index2word, idx ))
for cluster in range(0,10):

# Print the cluster number  
print ("\nCluster %d" % cluster)

# Find all of the words for that cluster number, and print them out
words = []
for i in range(0,len(word_centroid_map.values())):
    if( word_centroid_map.values()[i] == cluster ):
        words.append(word_centroid_map.keys()[i])
print (words)

我正在使用 python 3,我收到一条错误消息:

TypeError: 'dict_values' object does not support indexing

有人可以帮忙吗?提前致谢。

【问题讨论】:

  • 看起来您正试图在 Python 3 上运行(非常低效)Python 2 代码。
  • 如果您必须通过值搜索来获取感兴趣的键,这可能表明您的 dict 键控方式错误。

标签: python linguistics


【解决方案1】:

在 python3.x 中,dict.values() 不再返回一个列表——它返回一个dict_values 对象。您不能下标 dict_values 实例。例如

dict_values = some_dict.values()
dict_values[any_value]  # TypeError!

在这种情况下,看起来修复应该是停止使用索引并直接迭代字典的items

words = []
for key, item in word_centroid_map.items():
    if item == cluster:
        words.append(key)
print (words)

或者,作为一个列表理解:

words = [k for k, w in word_centroid_map.items() if w == cluster]

还请注意,这应该比相应的 python2.x 代码(在其中您重复生成列表以简单地丢弃它们并在下一个重新生成循环)。

【讨论】:

  • 不,您正在附加值。他正在附加密钥。
  • @wim -- 谢谢,我错过了。幸运的是,这很容易解决:-)
【解决方案2】:

作为对 mgilson 答案的补充/澄清:

dict.keys()、dict.values() 和 dict.items() 返回的对象 是视图对象。它们提供字典的动态视图 条目,这意味着当字典改变时,视图 反映了这些变化。 (https://docs.python.org/3/library/stdtypes.html#typesmapping)

【讨论】:

    【解决方案3】:

    您还可以使用list() 将dict_values、dict_keys 对象转换为列表:

    list( word_centroid_map.keys() )[i] 
    

    【讨论】:

      猜你喜欢
      • 2013-06-30
      • 2014-04-23
      • 2019-11-12
      • 2017-09-20
      • 1970-01-01
      • 1970-01-01
      • 2013-08-23
      • 2018-01-07
      • 2013-06-23
      相关资源
      最近更新 更多