Python 3: dict & dict.keys()

Ethan Furman ethan at stoneleaf.us
Wed Jul 24 16:16:54 EDT 2013


On 07/24/2013 12:59 PM, Stefan Behnel wrote:
>
> 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.

Thank you. :)

--
~Ethan~



More information about the Python-list mailing list