1

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)

doyz
  • 887
  • 2
  • 18
  • 43

2 Answers2

3

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]
Hannu
  • 11,685
  • 4
  • 35
  • 51
  • Hey, this does not return the "5" key-value pair, only 1 (i'm using python 2.7). Sorry , i wasn't clear, i want to return in a list values for "A" in both 1 and 5 – doyz Nov 23 '17 at 11:12
  • It does for me. – Hannu Nov 23 '17 at 11:15
  • Edited the answer with an example with your code (moved print total_A out of the for loop, though) – Hannu Nov 23 '17 at 11:18
  • Ok thanks, yeah i had to move print total_A out of the loop – doyz Nov 23 '17 at 11:28
  • Recommend using `for key,value in results.iteritems()` (python2) or `for key,value in results.items()` (python3), rather than doing a second lookup in the results dict. –  Nov 23 '17 at 11:58
0

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.

Syntaxén
  • 465
  • 1
  • 8
  • 15
  • Note that while `dict.items()` is standard approach in python3; for the OP it would be good to (also) include `dict.iteritems()` as it is arguably a more standard/common python2.7 approach. See here for why there is a difference, despite both "working" in python2: https://stackoverflow.com/questions/10458437/what-is-the-difference-between-dict-items-and-dict-iteritems (and also that `dict.viewitems()` exists in python2.7, when you expect to alter the dict during iteration) –  Nov 23 '17 at 12:01