for key, value in dict.<func>() - how to get? (which func)

D

dmitrey

hi all,
which method should I use to get iterator over (key, value) pairs for
Python dict, Python v 2.6 and above?

Of course I could use

for key in myDict.keys():
value = myDict.values()
# do something with the pair key, value

but searching each time for the value take some cputime that is
serious for the task involved

IIRC in python 2.5 I have something like keyvalues(), but I don't see
something like that in current dir(myDict).

Thank you in advance, D.
 
R

Rami Chowdhury

Hi Dmitrey,

I think what you're looking for is myDict.items(), or myDict.iteritems().

Cheers,
Rami
 
D

dmitrey

Yes, thank you, items() is the correct approach, on the other hand I
have already get rid of the cycle.
Regards, D.
 
G

Gary Duzan

hi all,
which method should I use to get iterator over (key, value) pairs for
Python dict, Python v 2.6 and above?

dict.iteritems()

Gary Duzan
Motorola H&NM
 
D

Diez B. Roggisch

dmitrey said:
Yes, thank you, items() is the correct approach, on the other hand I
have already get rid of the cycle.

Most certainly items() is *not* the correct approach if you are
concerned so much with performance, because items() first creates a list
of key/value-pairs, where iteritems() will be an effective iterator.

so if you are (IMHO wrongly) concerned about performance of an O(1)
lookup, items() certainly costs more.

And the following program proves it:

import time

d = dict(zip(xrange(100000), xrange(100000)))

start = time.time()
for loops in xrange(100):
for key in d:
value = d[key]

print "lookup: ", time.time() - start

start = time.time()

for loops in xrange(100):
for key, value in d.items():
value = d[key]


print "items: ", time.time() - start

start = time.time()

for loops in xrange(100):
for key, value in d.iteritems():
value = d[key]


print "items: ", time.time() - start


The result on my machine is:

deets$ python /tmp/test.py

lookup: 2.78633999825
items: 7.42830610275
items: 3.69960308075

So actually your condemed approach seems to be the fastest, where the
items() call by far is the slowest approch.

"In the face of ambiguity, refuse the temptation to guess."


Diez
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,962
Messages
2,570,134
Members
46,692
Latest member
JenniferTi

Latest Threads

Top