Loading ...
Sorry, an error occurred while loading the content.

Re: [python-iter] Digest Number 21

(184)
  • Magnus Lie Hetland
    Mar 14, 2001 Expand Messages
    View Source
    • 0 Attachment
      From: "Greg Wilson" <gvwilson@...>
      >
      > I agree that having "blah in dict" iterate over/check
      > keys, rather than the values, is the natural behavior.
      > I even think I know how to explain it to newcomers.
      > What I don't know is how to write a polymorphic function
      > to iterate over an arbitrary container, since:
      >
      > def column(x):
      > for i in x:
      > print i, "\t", x[i]
      >
      > doesn't work. Given an arbitrary object 'x', is there
      > some way for me to tell whether its iterator is generating
      > indices or values (or both)?

      Couldn't all containers have container.keys and container.values
      as two standard iterators? (And then we could even dispose of
      the aberration "for key in dict" <0.5 wink>.)

      Then something like

      def column(x):
      for i in x.keys:
      print i, "\t", x[i]

      should work on all containers. Or, of course:

      def column(x):
      for k, v in x.items:
      print k, "\t", v

      Oh, well. As far as I can recall, this point has been brought
      up in several forms before. (And .keys is perhaps not always
      meaningfull, as with sets, for instance.)

      --

      Magnus Lie Hetland http://www.hetland.org

      "Reality is what refuses to disappear when you stop
      believing in it" -- Philip K. Dick
    • Show all 6 messages in this topic