looping through the keys of a dictionary

Alex Martelli aleax at aleax.it
Thu Aug 23 09:45:42 EDT 2001


"Markus Schaber" <markus at schabi.de> wrote in message
news:1452000.a2XM6RcZxF at lunix.schabi.de...
> Burkhard Kloss <bk at xk7.com> schrub:
>
> >> Is there a way to loop through the keys of a dictionary (whitout
> >> using a list containing all those keys)?
> >>
> >> e.g. mydict = {'123':[1,9,13],'125':[6,8],'225':[5]}
> > for key in mydict.keys():
> >     print key, mydict [key]
> >
> > should do the trick
>
> It does, but
>
> >>> for key,value in mydict.items():
> ...     print key, value
>
> seems to be faster in my eyes, as it doesn't have a dictionary lookup
> every round.

SEEMS and IS, of course, are often very different, MOST
particularly in the arena of computer-program performance.
Have you tried to MEASURE things...?

File dipe.py:
import time

thedic = {}
for i in range(1000):
    thedic[i] = str(i)

def ignore(whatever):
    pass

def loop_on_keys(adic=thedic, times=100, ignore=ignore):
    for x in range(times):
        for key in adic.keys():
            ignore(adic[key])

def loop_on_items(adic=thedic, times=100, ignore=ignore):
    for x in range(times):
        for key, value in adic.items():
            ignore(value)

start = time.clock()
loop_on_keys()
stend = time.clock()
print 'using keys:',round(stend-start,2)

start = time.clock()
loop_on_items()
stend = time.clock()
print 'using items:',round(stend-start,2)

start = time.clock()
loop_on_keys()
stend = time.clock()
print 'using keys:',round(stend-start,2)

start = time.clock()
loop_on_items()
stend = time.clock()
print 'using items:',round(stend-start,2)


D:\py21>python dipe.py
using keys: 0.45
using items: 0.53
using keys: 0.45
using items: 0.53

D:\py21>python dipe.py
using keys: 0.45
using items: 0.53
using keys: 0.45
using items: 0.53


Highly repeatable on my box: the loop on items
is almost 20% slower than the loop on keys.
Sure, the latter has extra dict lookups, but
Python has *VERY* fast dict lookups -- the
former has a lot of extra construction of two-
item tuples (pairs), and apparently Python (in
this 2.1.1 version, on WinNT/4, etc etc, of
course) hasn't optimized that quite as much.


Alex






More information about the Python-list mailing list