简体   繁体   中英

How to populate Python dictionary using a loop

I am trying to populate this dictionary as I loop through, however when I print it to check, it seems like only the only element being added to the dictionary is the last item in the for loop. How can this be done?

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)

That's not the correct syntax for adding an element to a dict . You are just reseting the dict each time. You probably want

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

instead of

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

You are creating a new dict here in every iteration,

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

this should be

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

This is because you are creating a new dictionary in each iteration of your loop. Try the following:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM