我试图在循环时填充这个字典,但是当我打印它来检查时,似乎只有添加到字典中的唯一元素才是for循环中的最后一项。怎么办呢?
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)
答案 0 :(得分:6)
这不是将元素添加到dict
的正确语法。您只是每次重置dict
。你可能想要
probabilities[labels[j]] = results[j]
而不是
probabilities = {labels[j]:results[j]}
答案 1 :(得分:2)
您正在每次迭代中创建一个新的dict,
probabilities = {labels[j]:results[j]}
这应该是
probabilities[labels[j]] = results[j]
答案 2 :(得分:1)
这是因为您在循环的每次迭代中都创建了一个新字典。请尝试以下方法:
probabilities = {}
for j in top_k:
print(labels[j], results[j])
probabilities[labels[j]] = results[j]