php vs python

aonaran at aonaran at
Sun Jan 5 02:38:23 CET 2003

Afanasiy <abelikov72 at> wrote:

> How do I loop over an associative array (dictionary) with easy access
> to key and value variables on each iteration. In PHP I do this :

>  foreach($table as $key => $value) {
>    echo $key.'='.$value;
>  }

> In PHP, I am unsure how I am supposed to, in some way that makes sense,
> loop with access to the key in addition to the value (which is easy).

Assuming you mean it's not clear how to do this in python, the first way
that comes to mind is just this:

        # build easy dict
        d = {1:2,2:3,4:5,5:7,6:11}

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

With the introduction of iterators in python 2.2 (IIRC) it's even simpler:

        for key, val in d.items():
            print key,'=',val


Queen's University Astronomy Research Group
Planetary Dynamics Division                     "We create worlds."

More information about the Python-list mailing list