php vs python
aonaran at yahoo.com
aonaran at yahoo.com
Sat Jan 4 20:38:23 EST 2003
Afanasiy <abelikov72 at hotmail.com> 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
Doug
--
Queen's University Astronomy Research Group
Planetary Dynamics Division "We create worlds."
More information about the Python-list
mailing list