Dictionaries

Gary Herron gary.herron at islandtraining.com
Sun Feb 9 08:18:56 CET 2014


On 02/08/2014 11:07 PM, worthingtonclinton at gmail.com wrote:
> 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!
>
>
> Thanks in advance.

The lookup of a value in dictionary b does not care where the index 
comes from.    Quite simply, x has the value of 'blah', and b has 'blah' 
as a key, so b[x] works.

If a and b had different keys, then you would get an error:

 >>> a = {'a':1}
 >>> b = {'b':2}
 >>> for x in a:
...   print x
...   print a[x]
...   print b[x]
...
a
1
Traceback (most recent call last):
   File "<stdin>", line 4, in <module>
KeyError: 'a'


Gary Herron




More information about the Python-list mailing list