newbie question - iterating through dictionary object

Martin Christensen martin.sand.christensen at gmail.com
Thu Feb 17 11:40:29 EST 2005


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

>>>>> "Miranda" == mirandacascade  <mirandacascade at yahoo.com> writes:
Miranda> 1) Is there any advantage to use the
Miranda> y = a.keys()
Miranda> for z in y:

While you're at it, you could save y altogether and just use

for z in a.keys():
    ...

Miranda> looping technique rather than the
Miranda> for x in a:
Miranda> looping technique?

I certainly don't see any advatages.

Miranda> 2) What are the tradeoffs for using each of the techniques?

'for x in a:' is prettier to look at. :-) As you can see, it's also
slightly faster (at least for very small dictionaries), but unless
you're doing a _lot_ of them, it won't matter.

% python2.4 -m timeit -c "a = {1:1, 2:2, 3:3, 4:4, 5:5}" "for x in a: pass"
1000000 loops, best of 3: 1.63 usec per loop
% python2.4 -m timeit -c "a = {1:1, 2:2, 3:3, 4:4, 5:5}" "for x in a.keys(): pass"
100000 loops, best of 3: 2.1 usec per loop


Martin

- -- 
Homepage:       http://www.cs.auc.dk/~factotum/
GPG public key: http://www.cs.auc.dk/~factotum/gpgkey.txt
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.5 (GNU/Linux)
Comment: Using Mailcrypt+GnuPG <http://www.gnupg.org>

iEYEARECAAYFAkIUyPwACgkQYu1fMmOQldWV8ACdEZOgwwtOyp7c+hDVtQe+0LX1
yRoAoITJGZA6zA0iE9G4lp2cP/GinlZC
=njlP
-----END PGP SIGNATURE-----



More information about the Python-list mailing list