Something I'm confused about


once  = {'a': 1, 'b': 2}
twice = {'a': 2, 'b': 4}
for key in once:
    print "Once: %s" % once[key]
    print "Twice: %s" % twice[key]

In the case of for loops and dictionaries, what exactly is saved to (in this case) key?
In the prints below the loop, does the key in 'once[key]' refer to the dictionary or the loop?


well, you can see what is stored in key by printing it:

fore key in once:
   print key

dictionary's have key and values, in this case you store the keys in a variable called key, which then you use to access the values in the dictionary.

once is the dictionary name, key (thanks to the loop) contains the key value which you use to access the value from the one dictionary


So, by printing key, the string is what appears. How would one then print the value associated with that string?


uhm.. you do that here? once[key] you dictionary name + key to get the value, you could also manually use the actually key value:

print once['a']

but a loop is nice for all values in the dictionary


I see. Thanks for the explanation! :smiley: