Frank Millman frank at chagford.com
Sun Feb 9 08:27:37 CET 2014

<worthingtonclinton at gmail.com> wrote in message 
news:891d3696-4e4e-44cc-a491-6b8fef47fcd9 at googlegroups.com...
> why in a for loop can i access values for a dict that i did not address in 
> the for loop.
> example:
> a = {blah:blah}
> b = {blah:blah}
> for x in a:
>    print a[x]
>    #here's what i don't understand
>    print b[x]
>    # it would print the value for dict b even though it wasn't called upon 
> in the for loop!

Iterating over a dictionary returns the keys of the dictionary.

When you say 'for x in a', each iteration sets 'x' to the next key in 
dictionary 'a'.

'x' is a reference to a normal python object. It does not 'know' that it 
came from dictionary 'a', so you can do whatever you like with it. If you 
use it to retrieve a value in dictionary 'b', and the key happens to exist, 
it will return the value. Otherwise it will raise KeyError.


Frank Millman

More information about the Python-list mailing list