Python 3.5:Dict值对象不支持索引

时间:2016-11-11 14:56:10

标签: python python-3.x dictionary

我使用此代码在python 3.5中收到错误。错误是dict value object does not support indexing

#Find frequency of appearance for each value of the list
counter=collections.Counter(myList)
#Get frequencies' list
unique_freq = counter.values()
#Get unique items' list
unique_items=counter.keys()

probs= [(0,0)]*len(unique_items)

#Initialization of probs list
for i in range (0 , len(unique_items)):
        probs[i]=(unique_items[i],np.float32(unique_freq[i]))

2 个答案:

答案 0 :(得分:4)

您需要将.values()和.keys()结果转换为列表。

unique_freq = list(counter.values())

但更好的,pythonic做你想做的事情的方法是用items()迭代字典:

result = []

for key, value in your_dict.items():
    result.append((key,value))

答案 1 :(得分:1)

dict.keysdict.values都会返回类似的对象,这些对象不支持索引。

为了对它们编制索引,您需要将它们更改为支持它的对象,通常是list

#Get frequencies' list
unique_freq = list(counter.values())
#Get unique items' list
unique_items=list(counter.keys())