2017-08-09 64 views
0

我想填充此字典,因爲我循環,但是當我打印它檢查時,它似乎只有被添加到字典中的唯一元素是最後一項循環。如何才能做到這一點?如何使用循環填充Python字典

probabilities = {} 
with tf_Session(graph=graph) as sess: 
results = sess.run(output_operation.outputs[0], 
        {input_operation.outputs[0]:t}) 
results = np.squeeze(results) 

top_k = results.argsort()[-5:][::-1] 
labels = load_labels(label_files) 
for j in top_k: 
    print(labels[j], results[j]) 
    probabilities = {labels[j]:results[j]} 

print (probabilities) 
+1

'概率[標籤[J] =結果[J]' – Alexander

回答

4

這不是將元素添加到dict的正確語法。您只是每次重置dict。你可能想

probabilities[labels[j]] = results[j] 

,而不是

probabilities = {labels[j]:results[j]} 
+0

使得很多的意義,現在,謝謝:) – Veejay

2

您在每次迭代在這裏創建一個新的字典,

probabilities = {labels[j]:results[j]} 

這應該是

probabilities[labels[j]] = results[j] 
+1

得到它謝謝:) – Veejay

1

這是因爲你在每次迭代中創建一個新的字典你的循環。請嘗試以下操作:

probabilities = {} 
for j in top_k: 
    print(labels[j], results[j]) 
    probabilities[labels[j]] = results[j]