Python 3: dict & dict.keys()

Peter Otten __peter__ at web.de
Thu Jul 25 18:25:19 CEST 2013


Ian Kelly wrote:

> On Thu, Jul 25, 2013 at 2:13 AM, Peter Otten <__peter__ at web.de> wrote:
>> Chris Angelico wrote:
>>
>>> On Thu, Jul 25, 2013 at 5:04 PM, Steven D'Aprano
>>> <steve+comp.lang.python at pearwood.info> wrote:
>>>> - Views support efficient (O(1) in the case of keys) membership
>>>> testing, which neither iterkeys() nor Python2 keys() does.
>>>
>>> To save me the trouble and potential error of digging through the
>>> source code: What's the complexity of membership testing on
>>> values/items? Since you're calling it "efficient" it must be better
>>> than O(n) which the list form would be, yet it isn't O(1) or you
>>> wouldn't have qualified "in the case of keys". Does this mean
>>> membership testing of the values and items views is O(log n) in some
>>> way, eg a binary search?
>>
>> keys() and items() is O(1); both look up the key in the dictionary and
>> items() then proceeds to compare the value. values() is O(n).
> 
> 3.x values() is O(n) but avoids the unnecessary step of copying all the
> values in the dict that you get when performing the same operation
> using 2.x values().  Hence, although the asymptotic complexity is the
> same, it's still more efficient.

In Python 2 the prudent pythonista used itervalues() to avoid unnecessary 
intermediate list...




More information about the Python-list mailing list