Obviously, using values
, items
, and keys
is bad practice in Python 2.X in virtually every instance, because you'll allocate an extra list you don't actually need. Thus, for some time, the recommended best practice was to use iteritems
/itervalues
, and to use the built-in __iter__
if you wanted to enumerate the dict
's keys.
With the backport of Python 3's keys
, values
, and items
to Python 2.7 as viewkeys
, viewvalues
, and viewitems
, I'm wondering what the actual performance tradeoffs are of the view*
family of functions, vs. their iter*
counterparts. Is the only reason to continue using the iter*
functions that you are targeting Python 2.6 and earlier, or can the older iter*
methods be faster than the newer view*
methods in certain contexts?
Here's an answer addressing iterkeys
vs. viewkeys
here: https://stackoverflow.com/a/10190228/344143
Summary (with a little backstory): view*
methods are a live view into the data (that will update as it updates), whereas iter*
and just-plain *
are more like snapshots.
The linked answerer suggests that while the view*
-flavored methods may have a minor performance edge as well, there may be compatibility issues with the backport, and recommends continuing to use iter*
/*
under Python 2.
My take: if you want a live view and you're under Python 2, use view*
; if you just want to whip through the set of keys/values/items once, use iter*
; if you want to hang on to a snapshot of k/v/i for a bit (or iterate in some non-linear fashion), use *
. Let the performance slide until you pick it up in an inner loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With