container-indepentent iteration code ?

Jeremy Bowers jerf at jerf.org
Wed Sep 8 20:49:27 EDT 2004


On Wed, 08 Sep 2004 20:35:56 -0400, flacco wrote:
> i always want obj to be the value.  dicts, for example, yield keys 
> instead of values (i think?)...

Ah, that clarifies it for me. "Values" is a bit of an overloaded term. :-)

The problem you're running into here is that the "standard iterator" kind
of "defines" the "values" the container has. That's the only idea of
"default set of values in a container" that Python is going to understand. 

Thus, since the fundamental issue is a disagreement between you and Python
about what constitutes a "value" out of a dict (and as the human in this
transaction you are the right one :-) ), I don't see any way to avoid
explaining your idea to Python. You can make it convenient:

def values(iterable):
	if isinstance(iterable, dict):
		return iterable.itervalues()
	# Whatever other special cases you may need
	return iter(iterable)

for obj in values(container):
	# etc.

but there's no switch or anything that will do what you want. Sorry.
You're always going to have to explain what you mean by "whatever" to
Python.

Stepping up one meta-level, another possibility that you may consider is
creating some container classes that match whatever your heterogenous
containment needs are, then you can make *those* containers work naturally
without the function I showed above. Without knowing more about your
problem, I can't know if that is better in general.

Consider this:

class IterateGivesMeValues(dict):
	# It is quite likely your domain will give you a better
	# name :-)
	def __iter__(self):
		return self.itervalues()

igmv = IterateGivesMeValues()
igmv["key"] = "value"
for i in igmv:
	print i

will print "value" instead of "dict". If you build your structures out of
such objects your life may, or may not, be easier. 




More information about the Python-list mailing list