Dictionaries

  • Thread starter worthingtonclinton
  • Start date
W

worthingtonclinton

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.
 
G

Gary Herron

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:
.... 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
 
F

Frank Millman

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.

HTH

Frank Millman
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top