[Python-3000] Thoughts on dictionary views

Josiah Carlson jcarlson at uci.edu
Wed Feb 21 03:07:57 CET 2007

(merging a few replies to reduce traffic)

"Delaney, Timothy (Tim)" <tdelaney at avaya.com> wrote:
> Guido van Rossum wrote:
> > You can also think of dict views as a straightforward application of
> > the GoF adapter pattern.
> Yep - and I think that would be a good secondary explanation, instantly
> understandable by anyone with much programming experience.

Not necessarily.  I have been programming for almost a decade (most of
it in Python), and I haven't yet taken a software engineering course
(none were offered or required during my undergrad, and I didn't take
any in my masters program); so the whole "patterns" thing is generally
opaque to me.  Some of them are self-evident in the name (observer,
visitor, etc.), but "GoF adapter pattern" is Greek to me.

"Guido van Rossum" <guido at python.org> wrote:
> Perhaps it will be more palatable now that the views aren't mutable?
> Also, I think you may have the wrong semantic model -- it's not a
> self-updating view, it's just a different way to look at the same
> underlying mapping. (Did you see PEP 3106? Since you don't quote it
> this is not clear.)

I was "eh, why bother?" prior to reading the updated PEP 3106, but now
can see the benefit to keys(), values(), and items() returning views. 
I'm not sure I would use the added features (I don't believe I've ever
compared the equalities of keys or values of two dictionaries separately,
and I tend to stick to .iter*() methods), but I can also see how it
would be useful to some users.

"Guido van Rossum" <guido at python.org> wrote:
> On 2/20/07, Nick Coghlan <ncoghlan at gmail.com> wrote:
> > The speed costs may become negligible, but I believe the main concern
> > here is memory consumption (minimising memory usage is certainly the
> > only reason I've ever made sure to use the dict.iter* methods).
> As I said, it's still O(N) time and space, vs. O(1) for creating a view.

But that's only if the .keys(), .values(), .items() produced actual sets
versus producing a view.  In the case of .values(), I don't see how one
can do *any* better than O(n) for the a.values() == b.values() (or
really O(nlogn) for comparable objects, and O(n^2) when they are not).

There are going to be special cases that ruin performance with all 3
options (use Python 2.x equivalent .iter*(), use a view, use a set
variant).  While I can *see* the use of views, I can also see the
benefit with just renaming .iter*() as .*() .

 - Josiah

More information about the Python-3000 mailing list