Python 3: dict & dict.keys()

Stefan Behnel stefan_ml at behnel.de
Wed Jul 24 21:59:31 CEST 2013


Ethan Furman, 24.07.2013 20:31:
> On 07/24/2013 10:23 AM, Stefan Behnel wrote:
>> Peter Otten, 24.07.2013 08:23:
>>> Ethan Furman wrote:
>>>>
>>>> So, my question boils down to:  in Python 3 how is dict.keys() different
>>>> from dict?  What are the use cases?
>>>
>>> To me it looks like views are a solution waiting for a problem.
>>
>> They reduce the API overhead. Previously, you needed values() and
>> itervalues(), with values() being not more than a special case of what
>> itervalues() provides anyway. Now it's just one method that gives you
>> everything. It simply has corrected the tradeoff from two special purpose
>> APIs to one general purpose API, that's all.
> 
> I started this thread for two reasons:
> 
>   1) Increase awareness that using `list(dict)` is a cross-version
> replacement for `dict.keys()`
> 
>   2) Hopefully learn something about when a view is useful.
> 
> So far #2 is pretty much a failure.

I think the question is: how else would you implement an interface that
doesn't restrict itself to returning a list? I mean, previously, the
following was totally inefficient in terms of memory:

    value in d.values()

It now avoids creating an intermediate list copy of the values, thus
running with no additional memory overhead (well, a constant, ok, but
definitely not linear) and keeps users from resorting to the much more
unfriendly

    for v in d.itervalues():
        if v == value:
            return True
    else:
        return False

in order to achieve the same thing. You can now even efficiently do this
for items, i.e.

    (key, value) in d.items()

That's equivalent to "d[key] == value", but uses a different protocol,
meaning that you don't have to make a copy of the dict items in order to
pass it into something that works on a set or iterable of 2-tuples (which
is a way more generic interface than requiring a dict as input). These
things chain much more cleanly now, without first having to explain the
difference between items() and iteritems() and when to use which.

It's all about replacing the old copy-to-list interface by something that
is efficiently processable step by step. All of this started back when
iterators became a part of the language, then generators, and now dict
views. They may not be the hugest feature ever, but they definitely fit
into the language much better and much more cleanly than the old
copy-to-list way.

Ask yourself, if they had been there in Python 1.x, would you even have
thought about making the iter*() methods a part of the language? Would you
really have wanted a shorter way to create a list of dict values than
list(d.values())?

Stefan





More information about the Python-list mailing list