The Nightman
The Nightman

Reputation: 5759

Understanding value calling in python dictionary

I am reading through 'Programming Python' and I have the following code:

bob = {'name':'Bob Smith', 'age':42, 'pay':30000, 'job':'dev'}

for (key, record) in [('bob', bob)]:
    print(record)

And this prints out:

{'name':'Bob Smith', 'age':42, 'pay':30000, 'job':'dev'}

My confusion is that it looks to me like it is doing the same thing as this:

for record in bob:
    print(record)

But the above code prints out the keys and not values.

So my question is, what is the difference between the two for loops that causes them to print both keys and values or just keys?

Upvotes: 0

Views: 32

Answers (1)

BrenBarn
BrenBarn

Reputation: 251355

In for (key, record) in [('bob', bob)], you are not iterating over bob. You are iterating over [('bob', bob)] , which is a list with one element. That element is a tuple of two things, the string 'bob' and the object bob (which is a dictionary). Your loop assigns the first one to key and the second to record. But you don't do anything with key and just print record, so you print the dictionary.

In for record in bob you iterate over bob, which is a dictionary. Iterating over a dictionary gives you its keys, so you get its keys.

Upvotes: 2

Related Questions