php vs python

Carl Banks imbosol at vt.edu
Sun Jan 5 02:53:36 EST 2003


Afanasiy wrote:
> On Sat, 4 Jan 2003 21:21:05 -0500, pythonhda
> <pythonhda at yahoo.com.replacepythonwithlinux> wrote:
> 
>>for key in d:
>>       print key, '=', d[key]
> 
> Someone please verify this example is incorrect.

No, it's correct.  However, in versions of Python before 2.2, it won't
work because you cannot iterate over a dictionary.  You would have to
do it this way:

    for key in d.keys():
        print key, '=', d[key]


> Putting the value in a variable named 'key' still
> makes it a value, not a key... Right?
> 
> Wouldn't this code result in a no-index error on d[key] ?

No.  In Python (starting with 2.2), iterating over a dictionary
iterates through the keys, not the values.  Try this:

    d = { 'a': 1, 'b': 2, 'c': 3 }
    for x in d:
        print x

It will print the keys a, b, and c (in no particular order), not the
values 1, 2, and 3.  If you would like to iterate through the values
only, you could do this:

    for value in d.values():
        ...



-- 
CARL BANKS




More information about the Python-list mailing list