Reputation: 886
I have a dictionary with the following structure:
results =
{1: {'A': 10,
'B' : 11,
'C': 12},
5: {'A': 20,
'B' : 21,
'C': 22}}
I have tried to iterate through this dictionary using this for loop:
total_A = []
for key in results:
total_A.append(results[key]["A"])
print total_A
But it is not working, because it is inputting key as 1 and 2 each time it loops. How am i able to iterate through the results dictionary using index as 1 and 5? (they are of type integer)
Upvotes: 1
Views: 138
Reputation: 12205
Try this. It will loop through your dictionary keys.
for key in results.keys():
Like this:
total_A = []
for key in results.keys():
total_A.append(results[key]["A"])
print total_A
Result is
[10, 20]
Upvotes: 3
Reputation: 536
In your case you could do
for key, value in results.items():
total_A.append(value["A"])
Then value
will contain the value of the dictionary element, and you don't have to do the results[key]
lookup explicitly.
Upvotes: 0